babylon.max.js 4.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106
  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;
  6. if(!CANNON) {
  7. if(typeof exports === 'object') {
  8. try { CANNON = require("cannon"); } catch(e) {}
  9. } else if(typeof define === 'function' && define.amd) {
  10. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  11. }
  12. } else {
  13. if(typeof define === 'function' && define.amd) {
  14. if(!(require.specified && require.specified("' + dep.module + '"))) {
  15. try { define("cannon", [], function () { return CANNON; }); } catch(e) { }
  16. }
  17. amdDependencies.push("cannon");
  18. }
  19. }
  20. var OIMO = root. OIMO;
  21. if(!OIMO) {
  22. if(typeof exports === 'object') {
  23. try { OIMO = require("oimo"); } catch(e) {}
  24. } else if(typeof define === 'function' && define.amd) {
  25. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  26. }
  27. } else {
  28. if(typeof define === 'function' && define.amd) {
  29. if(!(require.specified && require.specified("' + dep.module + '"))) {
  30. try { define("oimo", [], function () { return OIMO; }); } catch(e) { }
  31. }
  32. amdDependencies.push("oimo");
  33. }
  34. }
  35. if(typeof exports === 'object' && typeof module === 'object')
  36. module.exports = factory(CANNON,OIMO);
  37. else if(typeof define === 'function' && define.amd)
  38. define("babylonjs", amdDependencies, factory);
  39. else if(typeof exports === 'object')
  40. exports["babylonjs"] = factory(CANNON,OIMO);
  41. else {
  42. root["BABYLON"] = factory(CANNON,OIMO);
  43. }
  44. })(this, function(CANNON,OIMO) {
  45. "use strict";
  46. var BABYLON;
  47. (function (BABYLON) {
  48. /**
  49. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  50. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  51. */
  52. var EffectFallbacks = /** @class */ (function () {
  53. function EffectFallbacks() {
  54. this._defines = {};
  55. this._currentRank = 32;
  56. this._maxRank = -1;
  57. }
  58. /**
  59. * Removes the fallback from the bound mesh.
  60. */
  61. EffectFallbacks.prototype.unBindMesh = function () {
  62. this._mesh = null;
  63. };
  64. /**
  65. * Adds a fallback on the specified property.
  66. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  67. * @param define The name of the define in the shader
  68. */
  69. EffectFallbacks.prototype.addFallback = function (rank, define) {
  70. if (!this._defines[rank]) {
  71. if (rank < this._currentRank) {
  72. this._currentRank = rank;
  73. }
  74. if (rank > this._maxRank) {
  75. this._maxRank = rank;
  76. }
  77. this._defines[rank] = new Array();
  78. }
  79. this._defines[rank].push(define);
  80. };
  81. /**
  82. * Sets the mesh to use CPU skinning when needing to fallback.
  83. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  84. * @param mesh The mesh to use the fallbacks.
  85. */
  86. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  87. this._mesh = mesh;
  88. if (rank < this._currentRank) {
  89. this._currentRank = rank;
  90. }
  91. if (rank > this._maxRank) {
  92. this._maxRank = rank;
  93. }
  94. };
  95. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  96. /**
  97. * Checks to see if more fallbacks are still availible.
  98. */
  99. get: function () {
  100. return this._currentRank <= this._maxRank;
  101. },
  102. enumerable: true,
  103. configurable: true
  104. });
  105. /**
  106. * Removes the defines that shoould be removed when falling back.
  107. * @param currentDefines defines the current define statements for the shader.
  108. * @param effect defines the current effect we try to compile
  109. * @returns The resulting defines with defines of the current rank removed.
  110. */
  111. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  112. // First we try to switch to CPU skinning
  113. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  114. this._mesh.computeBonesUsingShaders = false;
  115. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  116. var scene = this._mesh.getScene();
  117. for (var index = 0; index < scene.meshes.length; index++) {
  118. var otherMesh = scene.meshes[index];
  119. if (!otherMesh.material) {
  120. continue;
  121. }
  122. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  123. continue;
  124. }
  125. if (otherMesh.material.getEffect() === effect) {
  126. otherMesh.computeBonesUsingShaders = false;
  127. }
  128. else {
  129. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  130. var subMesh = _a[_i];
  131. var subMeshEffect = subMesh.effect;
  132. if (subMeshEffect === effect) {
  133. otherMesh.computeBonesUsingShaders = false;
  134. break;
  135. }
  136. }
  137. }
  138. }
  139. }
  140. else {
  141. var currentFallbacks = this._defines[this._currentRank];
  142. if (currentFallbacks) {
  143. for (var index = 0; index < currentFallbacks.length; index++) {
  144. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  145. }
  146. }
  147. this._currentRank++;
  148. }
  149. return currentDefines;
  150. };
  151. return EffectFallbacks;
  152. }());
  153. BABYLON.EffectFallbacks = EffectFallbacks;
  154. /**
  155. * Options to be used when creating an effect.
  156. */
  157. var EffectCreationOptions = /** @class */ (function () {
  158. function EffectCreationOptions() {
  159. }
  160. return EffectCreationOptions;
  161. }());
  162. BABYLON.EffectCreationOptions = EffectCreationOptions;
  163. /**
  164. * Effect containing vertex and fragment shader that can be executed on an object.
  165. */
  166. var Effect = /** @class */ (function () {
  167. /**
  168. * Instantiates an effect.
  169. * An effect can be used to create/manage/execute vertex and fragment shaders.
  170. * @param baseName Name of the effect.
  171. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  172. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  173. * @param samplers List of sampler variables that will be passed to the shader.
  174. * @param engine Engine to be used to render the effect
  175. * @param defines Define statements to be added to the shader.
  176. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  177. * @param onCompiled Callback that will be called when the shader is compiled.
  178. * @param onError Callback that will be called if an error occurs during shader compilation.
  179. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  180. */
  181. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  182. if (samplers === void 0) { samplers = null; }
  183. if (defines === void 0) { defines = null; }
  184. if (fallbacks === void 0) { fallbacks = null; }
  185. if (onCompiled === void 0) { onCompiled = null; }
  186. if (onError === void 0) { onError = null; }
  187. var _this = this;
  188. /**
  189. * Unique ID of the effect.
  190. */
  191. this.uniqueId = 0;
  192. /**
  193. * Observable that will be called when the shader is compiled.
  194. */
  195. this.onCompileObservable = new BABYLON.Observable();
  196. /**
  197. * Observable that will be called if an error occurs during shader compilation.
  198. */
  199. this.onErrorObservable = new BABYLON.Observable();
  200. /**
  201. * Observable that will be called when effect is bound.
  202. */
  203. this.onBindObservable = new BABYLON.Observable();
  204. this._uniformBuffersNames = {};
  205. this._isReady = false;
  206. this._compilationError = "";
  207. this.name = baseName;
  208. if (attributesNamesOrOptions.attributes) {
  209. var options = attributesNamesOrOptions;
  210. this._engine = uniformsNamesOrEngine;
  211. this._attributesNames = options.attributes;
  212. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  213. this._samplers = options.samplers;
  214. this.defines = options.defines;
  215. this.onError = options.onError;
  216. this.onCompiled = options.onCompiled;
  217. this._fallbacks = options.fallbacks;
  218. this._indexParameters = options.indexParameters;
  219. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  220. if (options.uniformBuffersNames) {
  221. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  222. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  223. }
  224. }
  225. }
  226. else {
  227. this._engine = engine;
  228. this.defines = defines;
  229. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  230. this._samplers = samplers;
  231. this._attributesNames = attributesNamesOrOptions;
  232. this.onError = onError;
  233. this.onCompiled = onCompiled;
  234. this._indexParameters = indexParameters;
  235. this._fallbacks = fallbacks;
  236. }
  237. this.uniqueId = Effect._uniqueIdSeed++;
  238. if (this._getFromCache(baseName)) {
  239. this._prepareEffect();
  240. return;
  241. }
  242. var vertexSource;
  243. var fragmentSource;
  244. if (baseName.vertexElement) {
  245. vertexSource = document.getElementById(baseName.vertexElement);
  246. if (!vertexSource) {
  247. vertexSource = baseName.vertexElement;
  248. }
  249. }
  250. else {
  251. vertexSource = baseName.vertex || baseName;
  252. }
  253. if (baseName.fragmentElement) {
  254. fragmentSource = document.getElementById(baseName.fragmentElement);
  255. if (!fragmentSource) {
  256. fragmentSource = baseName.fragmentElement;
  257. }
  258. }
  259. else {
  260. fragmentSource = baseName.fragment || baseName;
  261. }
  262. var finalVertexCode;
  263. this._loadVertexShaderAsync(vertexSource)
  264. .then(function (vertexCode) {
  265. return _this._processIncludesAsync(vertexCode);
  266. })
  267. .then(function (vertexCodeWithIncludes) {
  268. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  269. return _this._loadFragmentShaderAsync(fragmentSource);
  270. })
  271. .then(function (fragmentCode) {
  272. return _this._processIncludesAsync(fragmentCode);
  273. })
  274. .then(function (fragmentCodeWithIncludes) {
  275. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  276. if (baseName) {
  277. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  278. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  279. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  280. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  281. }
  282. else {
  283. _this._vertexSourceCode = finalVertexCode;
  284. _this._fragmentSourceCode = migratedFragmentCode;
  285. }
  286. _this._setInCache(baseName);
  287. _this._prepareEffect();
  288. });
  289. }
  290. Effect.prototype._getSourceCacheKey = function (baseName) {
  291. var cacheKey = baseName;
  292. if (this._indexParameters) {
  293. for (var key in this._indexParameters) {
  294. if (this._indexParameters.hasOwnProperty(key)) {
  295. cacheKey += "|";
  296. cacheKey += key;
  297. cacheKey += "_";
  298. cacheKey += this._indexParameters[key];
  299. }
  300. }
  301. }
  302. return cacheKey;
  303. };
  304. Effect.prototype._getFromCache = function (baseName) {
  305. if (typeof baseName !== "string") {
  306. return false;
  307. }
  308. var cacheKey = this._getSourceCacheKey(baseName);
  309. var sources = Effect._sourceCache[cacheKey];
  310. if (!sources) {
  311. return false;
  312. }
  313. this._vertexSourceCode = sources.vertex;
  314. this._fragmentSourceCode = sources.fragment;
  315. return true;
  316. };
  317. Effect.prototype._setInCache = function (baseName) {
  318. if (typeof baseName !== "string") {
  319. return;
  320. }
  321. var cacheKey = this._getSourceCacheKey(baseName);
  322. Effect._sourceCache[cacheKey] = {
  323. vertex: this._vertexSourceCode,
  324. fragment: this._fragmentSourceCode
  325. };
  326. };
  327. Object.defineProperty(Effect.prototype, "key", {
  328. /**
  329. * Unique key for this effect
  330. */
  331. get: function () {
  332. return this._key;
  333. },
  334. enumerable: true,
  335. configurable: true
  336. });
  337. /**
  338. * If the effect has been compiled and prepared.
  339. * @returns if the effect is compiled and prepared.
  340. */
  341. Effect.prototype.isReady = function () {
  342. return this._isReady;
  343. };
  344. /**
  345. * The engine the effect was initialized with.
  346. * @returns the engine.
  347. */
  348. Effect.prototype.getEngine = function () {
  349. return this._engine;
  350. };
  351. /**
  352. * The compiled webGL program for the effect
  353. * @returns the webGL program.
  354. */
  355. Effect.prototype.getProgram = function () {
  356. return this._program;
  357. };
  358. /**
  359. * The set of names of attribute variables for the shader.
  360. * @returns An array of attribute names.
  361. */
  362. Effect.prototype.getAttributesNames = function () {
  363. return this._attributesNames;
  364. };
  365. /**
  366. * Returns the attribute at the given index.
  367. * @param index The index of the attribute.
  368. * @returns The location of the attribute.
  369. */
  370. Effect.prototype.getAttributeLocation = function (index) {
  371. return this._attributes[index];
  372. };
  373. /**
  374. * Returns the attribute based on the name of the variable.
  375. * @param name of the attribute to look up.
  376. * @returns the attribute location.
  377. */
  378. Effect.prototype.getAttributeLocationByName = function (name) {
  379. var index = this._attributesNames.indexOf(name);
  380. return this._attributes[index];
  381. };
  382. /**
  383. * The number of attributes.
  384. * @returns the numnber of attributes.
  385. */
  386. Effect.prototype.getAttributesCount = function () {
  387. return this._attributes.length;
  388. };
  389. /**
  390. * Gets the index of a uniform variable.
  391. * @param uniformName of the uniform to look up.
  392. * @returns the index.
  393. */
  394. Effect.prototype.getUniformIndex = function (uniformName) {
  395. return this._uniformsNames.indexOf(uniformName);
  396. };
  397. /**
  398. * Returns the attribute based on the name of the variable.
  399. * @param uniformName of the uniform to look up.
  400. * @returns the location of the uniform.
  401. */
  402. Effect.prototype.getUniform = function (uniformName) {
  403. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  404. };
  405. /**
  406. * Returns an array of sampler variable names
  407. * @returns The array of sampler variable neames.
  408. */
  409. Effect.prototype.getSamplers = function () {
  410. return this._samplers;
  411. };
  412. /**
  413. * The error from the last compilation.
  414. * @returns the error string.
  415. */
  416. Effect.prototype.getCompilationError = function () {
  417. return this._compilationError;
  418. };
  419. /**
  420. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  421. * @param func The callback to be used.
  422. */
  423. Effect.prototype.executeWhenCompiled = function (func) {
  424. if (this.isReady()) {
  425. func(this);
  426. return;
  427. }
  428. this.onCompileObservable.add(function (effect) {
  429. func(effect);
  430. });
  431. };
  432. /** @ignore */
  433. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  434. if (BABYLON.Tools.IsWindowObjectExist()) {
  435. // DOM element ?
  436. if (vertex instanceof HTMLElement) {
  437. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  438. return Promise.resolve(vertexCode);
  439. }
  440. }
  441. // Base64 encoded ?
  442. if (vertex.substr(0, 7) === "base64:") {
  443. var vertexBinary = window.atob(vertex.substr(7));
  444. return Promise.resolve(vertexBinary);
  445. }
  446. // Is in local store ?
  447. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  448. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  449. }
  450. var vertexShaderUrl;
  451. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  452. vertexShaderUrl = vertex;
  453. }
  454. else {
  455. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  456. }
  457. // Vertex shader
  458. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  459. };
  460. /** @ignore */
  461. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  462. if (BABYLON.Tools.IsWindowObjectExist()) {
  463. // DOM element ?
  464. if (fragment instanceof HTMLElement) {
  465. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  466. return Promise.resolve(fragmentCode);
  467. }
  468. }
  469. // Base64 encoded ?
  470. if (fragment.substr(0, 7) === "base64:") {
  471. var fragmentBinary = window.atob(fragment.substr(7));
  472. return Promise.resolve(fragmentBinary);
  473. }
  474. // Is in local store ?
  475. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  476. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  477. }
  478. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  479. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  480. }
  481. var fragmentShaderUrl;
  482. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  483. fragmentShaderUrl = fragment;
  484. }
  485. else {
  486. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  487. }
  488. // Fragment shader
  489. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  490. };
  491. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  492. // Rebuild shaders source code
  493. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  494. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  495. vertexCode = prefix + vertexCode;
  496. fragmentCode = prefix + fragmentCode;
  497. // Number lines of shaders source code
  498. var i = 2;
  499. var regex = /\n/gm;
  500. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  501. i = 2;
  502. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  503. // Dump shaders name and formatted source code
  504. if (this.name.vertexElement) {
  505. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  506. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  507. }
  508. else if (this.name.vertex) {
  509. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  510. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  511. }
  512. else {
  513. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  514. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  515. }
  516. };
  517. ;
  518. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  519. var preparedSourceCode = this._processPrecision(sourceCode);
  520. if (this._engine.webGLVersion == 1) {
  521. return preparedSourceCode;
  522. }
  523. // Already converted
  524. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  525. return preparedSourceCode.replace("#version 300 es", "");
  526. }
  527. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  528. // Remove extensions
  529. // #extension GL_OES_standard_derivatives : enable
  530. // #extension GL_EXT_shader_texture_lod : enable
  531. // #extension GL_EXT_frag_depth : enable
  532. // #extension GL_EXT_draw_buffers : require
  533. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  534. var result = preparedSourceCode.replace(regex, "");
  535. // Migrate to GLSL v300
  536. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  537. result = result.replace(/attribute[ \t]/g, "in ");
  538. result = result.replace(/[ \t]attribute/g, " in");
  539. if (isFragment) {
  540. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  541. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  542. result = result.replace(/texture2D\s*\(/g, "texture(");
  543. result = result.replace(/textureCube\s*\(/g, "texture(");
  544. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  545. result = result.replace(/gl_FragColor/g, "glFragColor");
  546. result = result.replace(/gl_FragData/g, "glFragData");
  547. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  548. }
  549. return result;
  550. };
  551. Effect.prototype._processIncludesAsync = function (sourceCode) {
  552. var _this = this;
  553. return new Promise(function (resolve, reject) {
  554. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  555. var match = regex.exec(sourceCode);
  556. var returnValue = sourceCode;
  557. while (match != null) {
  558. var includeFile = match[1];
  559. // Uniform declaration
  560. if (includeFile.indexOf("__decl__") !== -1) {
  561. includeFile = includeFile.replace(/__decl__/, "");
  562. if (_this._engine.supportsUniformBuffers) {
  563. includeFile = includeFile.replace(/Vertex/, "Ubo");
  564. includeFile = includeFile.replace(/Fragment/, "Ubo");
  565. }
  566. includeFile = includeFile + "Declaration";
  567. }
  568. if (Effect.IncludesShadersStore[includeFile]) {
  569. // Substitution
  570. var includeContent = Effect.IncludesShadersStore[includeFile];
  571. if (match[2]) {
  572. var splits = match[3].split(",");
  573. for (var index = 0; index < splits.length; index += 2) {
  574. var source = new RegExp(splits[index], "g");
  575. var dest = splits[index + 1];
  576. includeContent = includeContent.replace(source, dest);
  577. }
  578. }
  579. if (match[4]) {
  580. var indexString = match[5];
  581. if (indexString.indexOf("..") !== -1) {
  582. var indexSplits = indexString.split("..");
  583. var minIndex = parseInt(indexSplits[0]);
  584. var maxIndex = parseInt(indexSplits[1]);
  585. var sourceIncludeContent = includeContent.slice(0);
  586. includeContent = "";
  587. if (isNaN(maxIndex)) {
  588. maxIndex = _this._indexParameters[indexSplits[1]];
  589. }
  590. for (var i = minIndex; i < maxIndex; i++) {
  591. if (!_this._engine.supportsUniformBuffers) {
  592. // Ubo replacement
  593. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  594. return p1 + "{X}";
  595. });
  596. }
  597. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  598. }
  599. }
  600. else {
  601. if (!_this._engine.supportsUniformBuffers) {
  602. // Ubo replacement
  603. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  604. return p1 + "{X}";
  605. });
  606. }
  607. includeContent = includeContent.replace(/\{X\}/g, indexString);
  608. }
  609. }
  610. // Replace
  611. returnValue = returnValue.replace(match[0], includeContent);
  612. }
  613. else {
  614. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  615. _this._engine._loadFileAsync(includeShaderUrl)
  616. .then(function (fileContent) {
  617. Effect.IncludesShadersStore[includeFile] = fileContent;
  618. return _this._processIncludesAsync(returnValue);
  619. })
  620. .then(function (returnValue) {
  621. resolve(returnValue);
  622. });
  623. return;
  624. }
  625. match = regex.exec(sourceCode);
  626. }
  627. resolve(returnValue);
  628. });
  629. };
  630. Effect.prototype._processPrecision = function (source) {
  631. if (source.indexOf("precision highp float") === -1) {
  632. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  633. source = "precision mediump float;\n" + source;
  634. }
  635. else {
  636. source = "precision highp float;\n" + source;
  637. }
  638. }
  639. else {
  640. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  641. source = source.replace("precision highp float", "precision mediump float");
  642. }
  643. }
  644. return source;
  645. };
  646. /**
  647. * Recompiles the webGL program
  648. * @param vertexSourceCode The source code for the vertex shader.
  649. * @param fragmentSourceCode The source code for the fragment shader.
  650. * @param onCompiled Callback called when completed.
  651. * @param onError Callback called on error.
  652. */
  653. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  654. var _this = this;
  655. this._isReady = false;
  656. this._vertexSourceCodeOverride = vertexSourceCode;
  657. this._fragmentSourceCodeOverride = fragmentSourceCode;
  658. this.onError = function (effect, error) {
  659. if (onError) {
  660. onError(error);
  661. }
  662. };
  663. this.onCompiled = function () {
  664. var scenes = _this.getEngine().scenes;
  665. for (var i = 0; i < scenes.length; i++) {
  666. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  667. }
  668. if (onCompiled) {
  669. onCompiled(_this._program);
  670. }
  671. };
  672. this._fallbacks = null;
  673. this._prepareEffect();
  674. };
  675. /**
  676. * Gets the uniform locations of the the specified variable names
  677. * @param names THe names of the variables to lookup.
  678. * @returns Array of locations in the same order as variable names.
  679. */
  680. Effect.prototype.getSpecificUniformLocations = function (names) {
  681. var engine = this._engine;
  682. return engine.getUniforms(this._program, names);
  683. };
  684. /**
  685. * Prepares the effect
  686. */
  687. Effect.prototype._prepareEffect = function () {
  688. var attributesNames = this._attributesNames;
  689. var defines = this.defines;
  690. var fallbacks = this._fallbacks;
  691. this._valueCache = {};
  692. var previousProgram = this._program;
  693. try {
  694. var engine = this._engine;
  695. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  696. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  697. }
  698. else {
  699. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  700. }
  701. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  702. if (engine.supportsUniformBuffers) {
  703. for (var name in this._uniformBuffersNames) {
  704. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  705. }
  706. }
  707. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  708. this._attributes = engine.getAttributes(this._program, attributesNames);
  709. var index;
  710. for (index = 0; index < this._samplers.length; index++) {
  711. var sampler = this.getUniform(this._samplers[index]);
  712. if (sampler == null) {
  713. this._samplers.splice(index, 1);
  714. index--;
  715. }
  716. }
  717. engine.bindSamplers(this);
  718. this._compilationError = "";
  719. this._isReady = true;
  720. if (this.onCompiled) {
  721. this.onCompiled(this);
  722. }
  723. this.onCompileObservable.notifyObservers(this);
  724. this.onCompileObservable.clear();
  725. // Unbind mesh reference in fallbacks
  726. if (this._fallbacks) {
  727. this._fallbacks.unBindMesh();
  728. }
  729. if (previousProgram) {
  730. this.getEngine()._deleteProgram(previousProgram);
  731. }
  732. }
  733. catch (e) {
  734. this._compilationError = e.message;
  735. // Let's go through fallbacks then
  736. BABYLON.Tools.Error("Unable to compile effect:");
  737. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  738. return " " + uniform;
  739. }));
  740. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  741. return " " + attribute;
  742. }));
  743. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  744. BABYLON.Tools.Error("Error: " + this._compilationError);
  745. if (previousProgram) {
  746. this._program = previousProgram;
  747. this._isReady = true;
  748. if (this.onError) {
  749. this.onError(this, this._compilationError);
  750. }
  751. this.onErrorObservable.notifyObservers(this);
  752. }
  753. if (fallbacks && fallbacks.isMoreFallbacks) {
  754. BABYLON.Tools.Error("Trying next fallback.");
  755. this.defines = fallbacks.reduce(this.defines, this);
  756. this._prepareEffect();
  757. }
  758. else {
  759. if (this.onError) {
  760. this.onError(this, this._compilationError);
  761. }
  762. this.onErrorObservable.notifyObservers(this);
  763. this.onErrorObservable.clear();
  764. // Unbind mesh reference in fallbacks
  765. if (this._fallbacks) {
  766. this._fallbacks.unBindMesh();
  767. }
  768. }
  769. }
  770. };
  771. Object.defineProperty(Effect.prototype, "isSupported", {
  772. /**
  773. * Checks if the effect is supported. (Must be called after compilation)
  774. */
  775. get: function () {
  776. return this._compilationError === "";
  777. },
  778. enumerable: true,
  779. configurable: true
  780. });
  781. /**
  782. * Binds a texture to the engine to be used as output of the shader.
  783. * @param channel Name of the output variable.
  784. * @param texture Texture to bind.
  785. */
  786. Effect.prototype._bindTexture = function (channel, texture) {
  787. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  788. };
  789. /**
  790. * Sets a texture on the engine to be used in the shader.
  791. * @param channel Name of the sampler variable.
  792. * @param texture Texture to set.
  793. */
  794. Effect.prototype.setTexture = function (channel, texture) {
  795. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  796. };
  797. /**
  798. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  799. * @param channel Name of the sampler variable.
  800. * @param texture Texture to set.
  801. */
  802. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  803. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  804. };
  805. /**
  806. * Sets an array of textures on the engine to be used in the shader.
  807. * @param channel Name of the variable.
  808. * @param textures Textures to set.
  809. */
  810. Effect.prototype.setTextureArray = function (channel, textures) {
  811. if (this._samplers.indexOf(channel + "Ex") === -1) {
  812. var initialPos = this._samplers.indexOf(channel);
  813. for (var index = 1; index < textures.length; index++) {
  814. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  815. }
  816. }
  817. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  818. };
  819. /**
  820. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  821. * 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)
  822. * @param channel Name of the sampler variable.
  823. * @param postProcess Post process to get the input texture from.
  824. */
  825. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  826. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  827. };
  828. /**
  829. * Sets the output texture of the passed in post process to be input of this effect.
  830. * @param channel Name of the sampler variable.
  831. * @param postProcess Post process to get the output texture from.
  832. */
  833. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  834. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  835. };
  836. /** @ignore */
  837. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  838. var cache = this._valueCache[uniformName];
  839. var flag = matrix.updateFlag;
  840. if (cache !== undefined && cache === flag) {
  841. return false;
  842. }
  843. this._valueCache[uniformName] = flag;
  844. return true;
  845. };
  846. /** @ignore */
  847. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  848. var cache = this._valueCache[uniformName];
  849. if (!cache) {
  850. cache = [x, y];
  851. this._valueCache[uniformName] = cache;
  852. return true;
  853. }
  854. var changed = false;
  855. if (cache[0] !== x) {
  856. cache[0] = x;
  857. changed = true;
  858. }
  859. if (cache[1] !== y) {
  860. cache[1] = y;
  861. changed = true;
  862. }
  863. return changed;
  864. };
  865. /** @ignore */
  866. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  867. var cache = this._valueCache[uniformName];
  868. if (!cache) {
  869. cache = [x, y, z];
  870. this._valueCache[uniformName] = cache;
  871. return true;
  872. }
  873. var changed = false;
  874. if (cache[0] !== x) {
  875. cache[0] = x;
  876. changed = true;
  877. }
  878. if (cache[1] !== y) {
  879. cache[1] = y;
  880. changed = true;
  881. }
  882. if (cache[2] !== z) {
  883. cache[2] = z;
  884. changed = true;
  885. }
  886. return changed;
  887. };
  888. /** @ignore */
  889. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  890. var cache = this._valueCache[uniformName];
  891. if (!cache) {
  892. cache = [x, y, z, w];
  893. this._valueCache[uniformName] = cache;
  894. return true;
  895. }
  896. var changed = false;
  897. if (cache[0] !== x) {
  898. cache[0] = x;
  899. changed = true;
  900. }
  901. if (cache[1] !== y) {
  902. cache[1] = y;
  903. changed = true;
  904. }
  905. if (cache[2] !== z) {
  906. cache[2] = z;
  907. changed = true;
  908. }
  909. if (cache[3] !== w) {
  910. cache[3] = w;
  911. changed = true;
  912. }
  913. return changed;
  914. };
  915. /**
  916. * Binds a buffer to a uniform.
  917. * @param buffer Buffer to bind.
  918. * @param name Name of the uniform variable to bind to.
  919. */
  920. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  921. var bufferName = this._uniformBuffersNames[name];
  922. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  923. return;
  924. }
  925. Effect._baseCache[bufferName] = buffer;
  926. this._engine.bindUniformBufferBase(buffer, bufferName);
  927. };
  928. /**
  929. * Binds block to a uniform.
  930. * @param blockName Name of the block to bind.
  931. * @param index Index to bind.
  932. */
  933. Effect.prototype.bindUniformBlock = function (blockName, index) {
  934. this._engine.bindUniformBlock(this._program, blockName, index);
  935. };
  936. /**
  937. * Sets an interger value on a uniform variable.
  938. * @param uniformName Name of the variable.
  939. * @param value Value to be set.
  940. * @returns this effect.
  941. */
  942. Effect.prototype.setInt = function (uniformName, value) {
  943. var cache = this._valueCache[uniformName];
  944. if (cache !== undefined && cache === value)
  945. return this;
  946. this._valueCache[uniformName] = value;
  947. this._engine.setInt(this.getUniform(uniformName), value);
  948. return this;
  949. };
  950. /**
  951. * Sets an int array on a uniform variable.
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setIntArray = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setIntArray(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * 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)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setIntArray2 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setIntArray2(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * 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)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setIntArray3 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setIntArray3(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * 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)
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setIntArray4 = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setIntArray4(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets an float array on a uniform variable.
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setFloatArray = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * 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)
  1007. * @param uniformName Name of the variable.
  1008. * @param array array to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1012. this._valueCache[uniformName] = null;
  1013. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1014. return this;
  1015. };
  1016. /**
  1017. * 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)
  1018. * @param uniformName Name of the variable.
  1019. * @param array array to be set.
  1020. * @returns this effect.
  1021. */
  1022. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1023. this._valueCache[uniformName] = null;
  1024. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1025. return this;
  1026. };
  1027. /**
  1028. * 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)
  1029. * @param uniformName Name of the variable.
  1030. * @param array array to be set.
  1031. * @returns this effect.
  1032. */
  1033. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1034. this._valueCache[uniformName] = null;
  1035. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets an array on a uniform variable.
  1040. * @param uniformName Name of the variable.
  1041. * @param array array to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setArray = function (uniformName, array) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setArray(this.getUniform(uniformName), array);
  1047. return this;
  1048. };
  1049. /**
  1050. * 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)
  1051. * @param uniformName Name of the variable.
  1052. * @param array array to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setArray2 = function (uniformName, array) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setArray2(this.getUniform(uniformName), array);
  1058. return this;
  1059. };
  1060. /**
  1061. * 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)
  1062. * @param uniformName Name of the variable.
  1063. * @param array array to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setArray3 = function (uniformName, array) {
  1067. this._valueCache[uniformName] = null;
  1068. this._engine.setArray3(this.getUniform(uniformName), array);
  1069. return this;
  1070. };
  1071. /**
  1072. * 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)
  1073. * @param uniformName Name of the variable.
  1074. * @param array array to be set.
  1075. * @returns this effect.
  1076. */
  1077. Effect.prototype.setArray4 = function (uniformName, array) {
  1078. this._valueCache[uniformName] = null;
  1079. this._engine.setArray4(this.getUniform(uniformName), array);
  1080. return this;
  1081. };
  1082. /**
  1083. * Sets matrices on a uniform variable.
  1084. * @param uniformName Name of the variable.
  1085. * @param matrices matrices to be set.
  1086. * @returns this effect.
  1087. */
  1088. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1089. if (!matrices) {
  1090. return this;
  1091. }
  1092. this._valueCache[uniformName] = null;
  1093. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1094. return this;
  1095. };
  1096. /**
  1097. * Sets matrix on a uniform variable.
  1098. * @param uniformName Name of the variable.
  1099. * @param matrix matrix to be set.
  1100. * @returns this effect.
  1101. */
  1102. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1103. if (this._cacheMatrix(uniformName, matrix)) {
  1104. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1105. }
  1106. return this;
  1107. };
  1108. /**
  1109. * 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)
  1110. * @param uniformName Name of the variable.
  1111. * @param matrix matrix to be set.
  1112. * @returns this effect.
  1113. */
  1114. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1115. this._valueCache[uniformName] = null;
  1116. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1117. return this;
  1118. };
  1119. /**
  1120. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1121. * @param uniformName Name of the variable.
  1122. * @param matrix matrix to be set.
  1123. * @returns this effect.
  1124. */
  1125. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1126. this._valueCache[uniformName] = null;
  1127. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1128. return this;
  1129. };
  1130. /**
  1131. * Sets a float on a uniform variable.
  1132. * @param uniformName Name of the variable.
  1133. * @param value value to be set.
  1134. * @returns this effect.
  1135. */
  1136. Effect.prototype.setFloat = function (uniformName, value) {
  1137. var cache = this._valueCache[uniformName];
  1138. if (cache !== undefined && cache === value)
  1139. return this;
  1140. this._valueCache[uniformName] = value;
  1141. this._engine.setFloat(this.getUniform(uniformName), value);
  1142. return this;
  1143. };
  1144. /**
  1145. * Sets a boolean on a uniform variable.
  1146. * @param uniformName Name of the variable.
  1147. * @param bool value to be set.
  1148. * @returns this effect.
  1149. */
  1150. Effect.prototype.setBool = function (uniformName, bool) {
  1151. var cache = this._valueCache[uniformName];
  1152. if (cache !== undefined && cache === bool)
  1153. return this;
  1154. this._valueCache[uniformName] = bool;
  1155. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1156. return this;
  1157. };
  1158. /**
  1159. * Sets a Vector2 on a uniform variable.
  1160. * @param uniformName Name of the variable.
  1161. * @param vector2 vector2 to be set.
  1162. * @returns this effect.
  1163. */
  1164. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1165. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1166. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1167. }
  1168. return this;
  1169. };
  1170. /**
  1171. * Sets a float2 on a uniform variable.
  1172. * @param uniformName Name of the variable.
  1173. * @param x First float in float2.
  1174. * @param y Second float in float2.
  1175. * @returns this effect.
  1176. */
  1177. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1178. if (this._cacheFloat2(uniformName, x, y)) {
  1179. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1180. }
  1181. return this;
  1182. };
  1183. /**
  1184. * Sets a Vector3 on a uniform variable.
  1185. * @param uniformName Name of the variable.
  1186. * @param vector3 Value to be set.
  1187. * @returns this effect.
  1188. */
  1189. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1190. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1191. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1192. }
  1193. return this;
  1194. };
  1195. /**
  1196. * Sets a float3 on a uniform variable.
  1197. * @param uniformName Name of the variable.
  1198. * @param x First float in float3.
  1199. * @param y Second float in float3.
  1200. * @param z Third float in float3.
  1201. * @returns this effect.
  1202. */
  1203. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1204. if (this._cacheFloat3(uniformName, x, y, z)) {
  1205. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1206. }
  1207. return this;
  1208. };
  1209. /**
  1210. * Sets a Vector4 on a uniform variable.
  1211. * @param uniformName Name of the variable.
  1212. * @param vector4 Value to be set.
  1213. * @returns this effect.
  1214. */
  1215. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1216. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1217. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1218. }
  1219. return this;
  1220. };
  1221. /**
  1222. * Sets a float4 on a uniform variable.
  1223. * @param uniformName Name of the variable.
  1224. * @param x First float in float4.
  1225. * @param y Second float in float4.
  1226. * @param z Third float in float4.
  1227. * @param w Fourth float in float4.
  1228. * @returns this effect.
  1229. */
  1230. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1231. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1232. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1233. }
  1234. return this;
  1235. };
  1236. /**
  1237. * Sets a Color3 on a uniform variable.
  1238. * @param uniformName Name of the variable.
  1239. * @param color3 Value to be set.
  1240. * @returns this effect.
  1241. */
  1242. Effect.prototype.setColor3 = function (uniformName, color3) {
  1243. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1244. this._engine.setColor3(this.getUniform(uniformName), color3);
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Sets a Color4 on a uniform variable.
  1250. * @param uniformName Name of the variable.
  1251. * @param color3 Value to be set.
  1252. * @param alpha Alpha value to be set.
  1253. * @returns this effect.
  1254. */
  1255. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1256. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1257. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1258. }
  1259. return this;
  1260. };
  1261. /**
  1262. * Sets a Color4 on a uniform variable
  1263. * @param uniformName defines the name of the variable
  1264. * @param color4 defines the value to be set
  1265. * @returns this effect.
  1266. */
  1267. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1268. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1269. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1270. }
  1271. return this;
  1272. };
  1273. /**
  1274. * Resets the cache of effects.
  1275. */
  1276. Effect.ResetCache = function () {
  1277. Effect._baseCache = {};
  1278. };
  1279. Effect._uniqueIdSeed = 0;
  1280. Effect._baseCache = {};
  1281. Effect._sourceCache = {};
  1282. // Statics
  1283. /**
  1284. * Store of each shader (The can be looked up using effect.key)
  1285. */
  1286. Effect.ShadersStore = {};
  1287. /**
  1288. * Store of each included file for a shader (The can be looked up using effect.key)
  1289. */
  1290. Effect.IncludesShadersStore = {};
  1291. return Effect;
  1292. }());
  1293. BABYLON.Effect = Effect;
  1294. })(BABYLON || (BABYLON = {}));
  1295. //# sourceMappingURL=babylon.effect.js.map
  1296. "use strict";
  1297. //# sourceMappingURL=babylon.types.js.map
  1298. "use strict";
  1299. var BABYLON;
  1300. (function (BABYLON) {
  1301. var KeyboardEventTypes = /** @class */ (function () {
  1302. function KeyboardEventTypes() {
  1303. }
  1304. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1305. get: function () {
  1306. return KeyboardEventTypes._KEYDOWN;
  1307. },
  1308. enumerable: true,
  1309. configurable: true
  1310. });
  1311. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1312. get: function () {
  1313. return KeyboardEventTypes._KEYUP;
  1314. },
  1315. enumerable: true,
  1316. configurable: true
  1317. });
  1318. KeyboardEventTypes._KEYDOWN = 0x01;
  1319. KeyboardEventTypes._KEYUP = 0x02;
  1320. return KeyboardEventTypes;
  1321. }());
  1322. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1323. var KeyboardInfo = /** @class */ (function () {
  1324. function KeyboardInfo(type, event) {
  1325. this.type = type;
  1326. this.event = event;
  1327. }
  1328. return KeyboardInfo;
  1329. }());
  1330. BABYLON.KeyboardInfo = KeyboardInfo;
  1331. /**
  1332. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1333. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1334. */
  1335. var KeyboardInfoPre = /** @class */ (function (_super) {
  1336. __extends(KeyboardInfoPre, _super);
  1337. function KeyboardInfoPre(type, event) {
  1338. var _this = _super.call(this, type, event) || this;
  1339. _this.skipOnPointerObservable = false;
  1340. return _this;
  1341. }
  1342. return KeyboardInfoPre;
  1343. }(KeyboardInfo));
  1344. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1345. })(BABYLON || (BABYLON = {}));
  1346. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1347. "use strict";
  1348. var BABYLON;
  1349. (function (BABYLON) {
  1350. var PointerEventTypes = /** @class */ (function () {
  1351. function PointerEventTypes() {
  1352. }
  1353. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1354. get: function () {
  1355. return PointerEventTypes._POINTERDOWN;
  1356. },
  1357. enumerable: true,
  1358. configurable: true
  1359. });
  1360. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1361. get: function () {
  1362. return PointerEventTypes._POINTERUP;
  1363. },
  1364. enumerable: true,
  1365. configurable: true
  1366. });
  1367. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1368. get: function () {
  1369. return PointerEventTypes._POINTERMOVE;
  1370. },
  1371. enumerable: true,
  1372. configurable: true
  1373. });
  1374. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1375. get: function () {
  1376. return PointerEventTypes._POINTERWHEEL;
  1377. },
  1378. enumerable: true,
  1379. configurable: true
  1380. });
  1381. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1382. get: function () {
  1383. return PointerEventTypes._POINTERPICK;
  1384. },
  1385. enumerable: true,
  1386. configurable: true
  1387. });
  1388. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1389. get: function () {
  1390. return PointerEventTypes._POINTERTAP;
  1391. },
  1392. enumerable: true,
  1393. configurable: true
  1394. });
  1395. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1396. get: function () {
  1397. return PointerEventTypes._POINTERDOUBLETAP;
  1398. },
  1399. enumerable: true,
  1400. configurable: true
  1401. });
  1402. PointerEventTypes._POINTERDOWN = 0x01;
  1403. PointerEventTypes._POINTERUP = 0x02;
  1404. PointerEventTypes._POINTERMOVE = 0x04;
  1405. PointerEventTypes._POINTERWHEEL = 0x08;
  1406. PointerEventTypes._POINTERPICK = 0x10;
  1407. PointerEventTypes._POINTERTAP = 0x20;
  1408. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1409. return PointerEventTypes;
  1410. }());
  1411. BABYLON.PointerEventTypes = PointerEventTypes;
  1412. var PointerInfoBase = /** @class */ (function () {
  1413. function PointerInfoBase(type, event) {
  1414. this.type = type;
  1415. this.event = event;
  1416. }
  1417. return PointerInfoBase;
  1418. }());
  1419. BABYLON.PointerInfoBase = PointerInfoBase;
  1420. /**
  1421. * This class is used to store pointer related info for the onPrePointerObservable event.
  1422. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1423. */
  1424. var PointerInfoPre = /** @class */ (function (_super) {
  1425. __extends(PointerInfoPre, _super);
  1426. function PointerInfoPre(type, event, localX, localY) {
  1427. var _this = _super.call(this, type, event) || this;
  1428. _this.skipOnPointerObservable = false;
  1429. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1430. return _this;
  1431. }
  1432. return PointerInfoPre;
  1433. }(PointerInfoBase));
  1434. BABYLON.PointerInfoPre = PointerInfoPre;
  1435. /**
  1436. * This type contains all the data related to a pointer event in Babylon.js.
  1437. * 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.
  1438. */
  1439. var PointerInfo = /** @class */ (function (_super) {
  1440. __extends(PointerInfo, _super);
  1441. function PointerInfo(type, event, pickInfo) {
  1442. var _this = _super.call(this, type, event) || this;
  1443. _this.pickInfo = pickInfo;
  1444. return _this;
  1445. }
  1446. return PointerInfo;
  1447. }(PointerInfoBase));
  1448. BABYLON.PointerInfo = PointerInfo;
  1449. })(BABYLON || (BABYLON = {}));
  1450. //# sourceMappingURL=babylon.pointerEvents.js.map
  1451. "use strict";
  1452. var BABYLON;
  1453. (function (BABYLON) {
  1454. BABYLON.ToGammaSpace = 1 / 2.2;
  1455. BABYLON.ToLinearSpace = 2.2;
  1456. BABYLON.Epsilon = 0.001;
  1457. /**
  1458. * Class used to hold a RBG color
  1459. */
  1460. var Color3 = /** @class */ (function () {
  1461. /**
  1462. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1463. * @param r defines the red component (between 0 and 1, default is 0)
  1464. * @param g defines the green component (between 0 and 1, default is 0)
  1465. * @param b defines the blue component (between 0 and 1, default is 0)
  1466. */
  1467. function Color3(
  1468. /**
  1469. * Defines the red component (between 0 and 1, default is 0)
  1470. */
  1471. r,
  1472. /**
  1473. * Defines the green component (between 0 and 1, default is 0)
  1474. */
  1475. g,
  1476. /**
  1477. * Defines the blue component (between 0 and 1, default is 0)
  1478. */
  1479. b) {
  1480. if (r === void 0) { r = 0; }
  1481. if (g === void 0) { g = 0; }
  1482. if (b === void 0) { b = 0; }
  1483. this.r = r;
  1484. this.g = g;
  1485. this.b = b;
  1486. }
  1487. /**
  1488. * Creates a string with the Color3 current values
  1489. * @returns the string representation of the Color3 object
  1490. */
  1491. Color3.prototype.toString = function () {
  1492. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1493. };
  1494. /**
  1495. * Returns the string "Color3"
  1496. * @returns "Color3"
  1497. */
  1498. Color3.prototype.getClassName = function () {
  1499. return "Color3";
  1500. };
  1501. /**
  1502. * Compute the Color3 hash code
  1503. * @returns an unique number that can be used to hash Color3 objects
  1504. */
  1505. Color3.prototype.getHashCode = function () {
  1506. var hash = this.r || 0;
  1507. hash = (hash * 397) ^ (this.g || 0);
  1508. hash = (hash * 397) ^ (this.b || 0);
  1509. return hash;
  1510. };
  1511. // Operators
  1512. /**
  1513. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1514. * @param array defines the array where to store the r,g,b components
  1515. * @param index defines an optional index in the target array to define where to start storing values
  1516. * @returns the current Color3 object
  1517. */
  1518. Color3.prototype.toArray = function (array, index) {
  1519. if (index === undefined) {
  1520. index = 0;
  1521. }
  1522. array[index] = this.r;
  1523. array[index + 1] = this.g;
  1524. array[index + 2] = this.b;
  1525. return this;
  1526. };
  1527. /**
  1528. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1529. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1530. * @returns a new {BABYLON.Color4} object
  1531. */
  1532. Color3.prototype.toColor4 = function (alpha) {
  1533. if (alpha === void 0) { alpha = 1; }
  1534. return new Color4(this.r, this.g, this.b, alpha);
  1535. };
  1536. /**
  1537. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1538. * @returns the new array
  1539. */
  1540. Color3.prototype.asArray = function () {
  1541. var result = new Array();
  1542. this.toArray(result, 0);
  1543. return result;
  1544. };
  1545. /**
  1546. * Returns the luminance value
  1547. * @returns a float value
  1548. */
  1549. Color3.prototype.toLuminance = function () {
  1550. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1551. };
  1552. /**
  1553. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1554. * @param otherColor defines the second operand
  1555. * @returns the new Color3 object
  1556. */
  1557. Color3.prototype.multiply = function (otherColor) {
  1558. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1559. };
  1560. /**
  1561. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1562. * @param otherColor defines the second operand
  1563. * @param result defines the Color3 object where to store the result
  1564. * @returns the current Color3
  1565. */
  1566. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1567. result.r = this.r * otherColor.r;
  1568. result.g = this.g * otherColor.g;
  1569. result.b = this.b * otherColor.b;
  1570. return this;
  1571. };
  1572. /**
  1573. * Determines equality between Color3 objects
  1574. * @param otherColor defines the second operand
  1575. * @returns true if the rgb values are equal to the passed ones
  1576. */
  1577. Color3.prototype.equals = function (otherColor) {
  1578. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1579. };
  1580. /**
  1581. * Determines equality between the current Color3 object and a set of r,b,g values
  1582. * @param r defines the red component to check
  1583. * @param g defines the green component to check
  1584. * @param b defines the blue component to check
  1585. * @returns true if the rgb values are equal to the passed ones
  1586. */
  1587. Color3.prototype.equalsFloats = function (r, g, b) {
  1588. return this.r === r && this.g === g && this.b === b;
  1589. };
  1590. /**
  1591. * Multiplies in place each rgb value by scale
  1592. * @param scale defines the scaling factor
  1593. * @returns the updated Color3
  1594. */
  1595. Color3.prototype.scale = function (scale) {
  1596. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1597. };
  1598. /**
  1599. * Multiplies the rgb values by scale and stores the result into "result"
  1600. * @param scale defines the scaling factor
  1601. * @param result defines the Color3 object where to store the result
  1602. * @returns the unmodified current Color3
  1603. */
  1604. Color3.prototype.scaleToRef = function (scale, result) {
  1605. result.r = this.r * scale;
  1606. result.g = this.g * scale;
  1607. result.b = this.b * scale;
  1608. return this;
  1609. };
  1610. /**
  1611. * Scale the current Color3 values by a factor and add the result to a given Color3
  1612. * @param scale defines the scale factor
  1613. * @param result defines color to store the result into
  1614. * @returns the unmodified current Color3
  1615. */
  1616. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1617. result.r += this.r * scale;
  1618. result.g += this.g * scale;
  1619. result.b += this.b * scale;
  1620. return this;
  1621. };
  1622. /**
  1623. * Clamps the rgb values by the min and max values and stores the result into "result"
  1624. * @param min defines minimum clamping value (default is 0)
  1625. * @param max defines maximum clamping value (default is 1)
  1626. * @param result defines color to store the result into
  1627. * @returns the original Color3
  1628. */
  1629. Color3.prototype.clampToRef = function (min, max, result) {
  1630. if (min === void 0) { min = 0; }
  1631. if (max === void 0) { max = 1; }
  1632. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1633. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1634. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1635. return this;
  1636. };
  1637. /**
  1638. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1639. * @param otherColor defines the second operand
  1640. * @returns the new Color3
  1641. */
  1642. Color3.prototype.add = function (otherColor) {
  1643. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1644. };
  1645. /**
  1646. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1647. * @param otherColor defines the second operand
  1648. * @param result defines Color3 object to store the result into
  1649. * @returns the unmodified current Color3
  1650. */
  1651. Color3.prototype.addToRef = function (otherColor, result) {
  1652. result.r = this.r + otherColor.r;
  1653. result.g = this.g + otherColor.g;
  1654. result.b = this.b + otherColor.b;
  1655. return this;
  1656. };
  1657. /**
  1658. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1659. * @param otherColor defines the second operand
  1660. * @returns the new Color3
  1661. */
  1662. Color3.prototype.subtract = function (otherColor) {
  1663. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1664. };
  1665. /**
  1666. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1667. * @param otherColor defines the second operand
  1668. * @param result defines Color3 object to store the result into
  1669. * @returns the unmodified current Color3
  1670. */
  1671. Color3.prototype.subtractToRef = function (otherColor, result) {
  1672. result.r = this.r - otherColor.r;
  1673. result.g = this.g - otherColor.g;
  1674. result.b = this.b - otherColor.b;
  1675. return this;
  1676. };
  1677. /**
  1678. * Copy the current object
  1679. * @returns a new Color3 copied the current one
  1680. */
  1681. Color3.prototype.clone = function () {
  1682. return new Color3(this.r, this.g, this.b);
  1683. };
  1684. /**
  1685. * Copies the rgb values from the source in the current Color3
  1686. * @param source defines the source Color3 object
  1687. * @returns the updated Color3 object
  1688. */
  1689. Color3.prototype.copyFrom = function (source) {
  1690. this.r = source.r;
  1691. this.g = source.g;
  1692. this.b = source.b;
  1693. return this;
  1694. };
  1695. /**
  1696. * Updates the Color3 rgb values from the passed floats
  1697. * @param r defines the red component to read from
  1698. * @param g defines the green component to read from
  1699. * @param b defines the blue component to read from
  1700. * @returns the current Color3 object
  1701. */
  1702. Color3.prototype.copyFromFloats = function (r, g, b) {
  1703. this.r = r;
  1704. this.g = g;
  1705. this.b = b;
  1706. return this;
  1707. };
  1708. /**
  1709. * Updates the Color3 rgb values from the passed floats
  1710. * @param r defines the red component to read from
  1711. * @param g defines the green component to read from
  1712. * @param b defines the blue component to read from
  1713. * @returns the current Color3 object
  1714. */
  1715. Color3.prototype.set = function (r, g, b) {
  1716. return this.copyFromFloats(r, g, b);
  1717. };
  1718. /**
  1719. * Compute the Color3 hexadecimal code as a string
  1720. * @returns a string containing the hexadecimal representation of the Color3 object
  1721. */
  1722. Color3.prototype.toHexString = function () {
  1723. var intR = (this.r * 255) | 0;
  1724. var intG = (this.g * 255) | 0;
  1725. var intB = (this.b * 255) | 0;
  1726. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1727. };
  1728. /**
  1729. * Computes a new Color3 converted from the current one to linear space
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.prototype.toLinearSpace = function () {
  1733. var convertedColor = new Color3();
  1734. this.toLinearSpaceToRef(convertedColor);
  1735. return convertedColor;
  1736. };
  1737. /**
  1738. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1739. * @param convertedColor defines the Color3 object where to store the linear space version
  1740. * @returns the unmodified Color3
  1741. */
  1742. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1743. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1744. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1745. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1746. return this;
  1747. };
  1748. /**
  1749. * Computes a new Color3 converted from the current one to gamma space
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.prototype.toGammaSpace = function () {
  1753. var convertedColor = new Color3();
  1754. this.toGammaSpaceToRef(convertedColor);
  1755. return convertedColor;
  1756. };
  1757. /**
  1758. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1759. * @param convertedColor defines the Color3 object where to store the gamma space version
  1760. * @returns the unmodified Color3
  1761. */
  1762. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1763. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1764. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1765. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1766. return this;
  1767. };
  1768. // Statics
  1769. /**
  1770. * Creates a new Color3 from the string containing valid hexadecimal values
  1771. * @param hex defines a string containing valid hexadecimal values
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.FromHexString = function (hex) {
  1775. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1776. return new Color3(0, 0, 0);
  1777. }
  1778. var r = parseInt(hex.substring(1, 3), 16);
  1779. var g = parseInt(hex.substring(3, 5), 16);
  1780. var b = parseInt(hex.substring(5, 7), 16);
  1781. return Color3.FromInts(r, g, b);
  1782. };
  1783. /**
  1784. * Creates a new Vector3 from the starting index of the passed array
  1785. * @param array defines the source array
  1786. * @param offset defines an offset in the source array
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.FromArray = function (array, offset) {
  1790. if (offset === void 0) { offset = 0; }
  1791. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1792. };
  1793. /**
  1794. * Creates a new Color3 from integer values (< 256)
  1795. * @param r defines the red component to read from (value between 0 and 255)
  1796. * @param g defines the green component to read from (value between 0 and 255)
  1797. * @param b defines the blue component to read from (value between 0 and 255)
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.FromInts = function (r, g, b) {
  1801. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1802. };
  1803. /**
  1804. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1805. * @param start defines the start Color3 value
  1806. * @param end defines the end Color3 value
  1807. * @param amount defines the gradient value between start and end
  1808. * @returns a new Color3 object
  1809. */
  1810. Color3.Lerp = function (start, end, amount) {
  1811. var r = start.r + ((end.r - start.r) * amount);
  1812. var g = start.g + ((end.g - start.g) * amount);
  1813. var b = start.b + ((end.b - start.b) * amount);
  1814. return new Color3(r, g, b);
  1815. };
  1816. /**
  1817. * Returns a Color3 value containing a red color
  1818. * @returns a new Color3 object
  1819. */
  1820. Color3.Red = function () { return new Color3(1, 0, 0); };
  1821. /**
  1822. * Returns a Color3 value containing a green color
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.Green = function () { return new Color3(0, 1, 0); };
  1826. /**
  1827. * Returns a Color3 value containing a blue color
  1828. * @returns a new Color3 object
  1829. */
  1830. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1831. /**
  1832. * Returns a Color3 value containing a black color
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Black = function () { return new Color3(0, 0, 0); };
  1836. /**
  1837. * Returns a Color3 value containing a white color
  1838. * @returns a new Color3 object
  1839. */
  1840. Color3.White = function () { return new Color3(1, 1, 1); };
  1841. /**
  1842. * Returns a Color3 value containing a purple color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1846. /**
  1847. * Returns a Color3 value containing a magenta color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1851. /**
  1852. * Returns a Color3 value containing a yellow color
  1853. * @returns a new Color3 object
  1854. */
  1855. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1856. /**
  1857. * Returns a Color3 value containing a gray color
  1858. * @returns a new Color3 object
  1859. */
  1860. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1861. /**
  1862. * Returns a Color3 value containing a teal color
  1863. * @returns a new Color3 object
  1864. */
  1865. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1866. /**
  1867. * Returns a Color3 value containing a random color
  1868. * @returns a new Color3 object
  1869. */
  1870. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1871. return Color3;
  1872. }());
  1873. BABYLON.Color3 = Color3;
  1874. /**
  1875. * Class used to hold a RBGA color
  1876. */
  1877. var Color4 = /** @class */ (function () {
  1878. /**
  1879. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1880. * @param r defines the red component (between 0 and 1, default is 0)
  1881. * @param g defines the green component (between 0 and 1, default is 0)
  1882. * @param b defines the blue component (between 0 and 1, default is 0)
  1883. * @param a defines the alpha component (between 0 and 1, default is 1)
  1884. */
  1885. function Color4(
  1886. /**
  1887. * Defines the red component (between 0 and 1, default is 0)
  1888. */
  1889. r,
  1890. /**
  1891. * Defines the green component (between 0 and 1, default is 0)
  1892. */
  1893. g,
  1894. /**
  1895. * Defines the blue component (between 0 and 1, default is 0)
  1896. */
  1897. b,
  1898. /**
  1899. * Defines the alpha component (between 0 and 1, default is 1)
  1900. */
  1901. a) {
  1902. if (r === void 0) { r = 0; }
  1903. if (g === void 0) { g = 0; }
  1904. if (b === void 0) { b = 0; }
  1905. if (a === void 0) { a = 1; }
  1906. this.r = r;
  1907. this.g = g;
  1908. this.b = b;
  1909. this.a = a;
  1910. }
  1911. // Operators
  1912. /**
  1913. * Adds in place the passed Color4 values to the current Color4 object
  1914. * @param right defines the second operand
  1915. * @returns the current updated Color4 object
  1916. */
  1917. Color4.prototype.addInPlace = function (right) {
  1918. this.r += right.r;
  1919. this.g += right.g;
  1920. this.b += right.b;
  1921. this.a += right.a;
  1922. return this;
  1923. };
  1924. /**
  1925. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1926. * @returns the new array
  1927. */
  1928. Color4.prototype.asArray = function () {
  1929. var result = new Array();
  1930. this.toArray(result, 0);
  1931. return result;
  1932. };
  1933. /**
  1934. * Stores from the starting index in the passed array the Color4 successive values
  1935. * @param array defines the array where to store the r,g,b components
  1936. * @param index defines an optional index in the target array to define where to start storing values
  1937. * @returns the current Color4 object
  1938. */
  1939. Color4.prototype.toArray = function (array, index) {
  1940. if (index === undefined) {
  1941. index = 0;
  1942. }
  1943. array[index] = this.r;
  1944. array[index + 1] = this.g;
  1945. array[index + 2] = this.b;
  1946. array[index + 3] = this.a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1951. * @param right defines the second operand
  1952. * @returns a new Color4 object
  1953. */
  1954. Color4.prototype.add = function (right) {
  1955. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1956. };
  1957. /**
  1958. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1959. * @param right defines the second operand
  1960. * @returns a new Color4 object
  1961. */
  1962. Color4.prototype.subtract = function (right) {
  1963. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1964. };
  1965. /**
  1966. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1967. * @param right defines the second operand
  1968. * @param result defines the Color4 object where to store the result
  1969. * @returns the current Color4 object
  1970. */
  1971. Color4.prototype.subtractToRef = function (right, result) {
  1972. result.r = this.r - right.r;
  1973. result.g = this.g - right.g;
  1974. result.b = this.b - right.b;
  1975. result.a = this.a - right.a;
  1976. return this;
  1977. };
  1978. /**
  1979. * Creates a new Color4 with the current Color4 values multiplied by scale
  1980. * @param scale defines the scaling factor to apply
  1981. * @returns a new Color4 object
  1982. */
  1983. Color4.prototype.scale = function (scale) {
  1984. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1985. };
  1986. /**
  1987. * Multiplies the current Color4 values by scale and stores the result in "result"
  1988. * @param scale defines the scaling factor to apply
  1989. * @param result defines the Color4 object where to store the result
  1990. * @returns the current unmodified Color4
  1991. */
  1992. Color4.prototype.scaleToRef = function (scale, result) {
  1993. result.r = this.r * scale;
  1994. result.g = this.g * scale;
  1995. result.b = this.b * scale;
  1996. result.a = this.a * scale;
  1997. return this;
  1998. };
  1999. /**
  2000. * Scale the current Color4 values by a factor and add the result to a given Color4
  2001. * @param scale defines the scale factor
  2002. * @param result defines the Color4 object where to store the result
  2003. * @returns the unmodified current Color4
  2004. */
  2005. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2006. result.r += this.r * scale;
  2007. result.g += this.g * scale;
  2008. result.b += this.b * scale;
  2009. result.a += this.a * scale;
  2010. return this;
  2011. };
  2012. /**
  2013. * Clamps the rgb values by the min and max values and stores the result into "result"
  2014. * @param min defines minimum clamping value (default is 0)
  2015. * @param max defines maximum clamping value (default is 1)
  2016. * @param result defines color to store the result into.
  2017. * @returns the cuurent Color4
  2018. */
  2019. Color4.prototype.clampToRef = function (min, max, result) {
  2020. if (min === void 0) { min = 0; }
  2021. if (max === void 0) { max = 1; }
  2022. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2023. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2024. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2025. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2026. return this;
  2027. };
  2028. /**
  2029. * Multipy an Color4 value by another and return a new Color4 object
  2030. * @param color defines the Color4 value to multiply by
  2031. * @returns a new Color4 object
  2032. */
  2033. Color4.prototype.multiply = function (color) {
  2034. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2035. };
  2036. /**
  2037. * Multipy a Color4 value by another and push the result in a reference value
  2038. * @param color defines the Color4 value to multiply by
  2039. * @param result defines the Color4 to fill the result in
  2040. * @returns the result Color4
  2041. */
  2042. Color4.prototype.multiplyToRef = function (color, result) {
  2043. result.r = this.r * color.r;
  2044. result.g = this.g * color.g;
  2045. result.b = this.b * color.b;
  2046. result.a = this.a * color.a;
  2047. return result;
  2048. };
  2049. /**
  2050. * Creates a string with the Color4 current values
  2051. * @returns the string representation of the Color4 object
  2052. */
  2053. Color4.prototype.toString = function () {
  2054. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2055. };
  2056. /**
  2057. * Returns the string "Color4"
  2058. * @returns "Color4"
  2059. */
  2060. Color4.prototype.getClassName = function () {
  2061. return "Color4";
  2062. };
  2063. /**
  2064. * Compute the Color4 hash code
  2065. * @returns an unique number that can be used to hash Color4 objects
  2066. */
  2067. Color4.prototype.getHashCode = function () {
  2068. var hash = this.r || 0;
  2069. hash = (hash * 397) ^ (this.g || 0);
  2070. hash = (hash * 397) ^ (this.b || 0);
  2071. hash = (hash * 397) ^ (this.a || 0);
  2072. return hash;
  2073. };
  2074. /**
  2075. * Creates a new Color4 copied from the current one
  2076. * @returns a new Color4 object
  2077. */
  2078. Color4.prototype.clone = function () {
  2079. return new Color4(this.r, this.g, this.b, this.a);
  2080. };
  2081. /**
  2082. * Copies the passed Color4 values into the current one
  2083. * @param source defines the source Color4 object
  2084. * @returns the current updated Color4 object
  2085. */
  2086. Color4.prototype.copyFrom = function (source) {
  2087. this.r = source.r;
  2088. this.g = source.g;
  2089. this.b = source.b;
  2090. this.a = source.a;
  2091. return this;
  2092. };
  2093. /**
  2094. * Copies the passed float values into the current one
  2095. * @param r defines the red component to read from
  2096. * @param g defines the green component to read from
  2097. * @param b defines the blue component to read from
  2098. * @param a defines the alpha component to read from
  2099. * @returns the current updated Color4 object
  2100. */
  2101. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2102. this.r = r;
  2103. this.g = g;
  2104. this.b = b;
  2105. this.a = a;
  2106. return this;
  2107. };
  2108. /**
  2109. * Copies the passed float values into the current one
  2110. * @param r defines the red component to read from
  2111. * @param g defines the green component to read from
  2112. * @param b defines the blue component to read from
  2113. * @param a defines the alpha component to read from
  2114. * @returns the current updated Color4 object
  2115. */
  2116. Color4.prototype.set = function (r, g, b, a) {
  2117. return this.copyFromFloats(r, g, b, a);
  2118. };
  2119. /**
  2120. * Compute the Color4 hexadecimal code as a string
  2121. * @returns a string containing the hexadecimal representation of the Color4 object
  2122. */
  2123. Color4.prototype.toHexString = function () {
  2124. var intR = (this.r * 255) | 0;
  2125. var intG = (this.g * 255) | 0;
  2126. var intB = (this.b * 255) | 0;
  2127. var intA = (this.a * 255) | 0;
  2128. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2129. };
  2130. /**
  2131. * Computes a new Color4 converted from the current one to linear space
  2132. * @returns a new Color4 object
  2133. */
  2134. Color4.prototype.toLinearSpace = function () {
  2135. var convertedColor = new Color4();
  2136. this.toLinearSpaceToRef(convertedColor);
  2137. return convertedColor;
  2138. };
  2139. /**
  2140. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2141. * @param convertedColor defines the Color4 object where to store the linear space version
  2142. * @returns the unmodified Color4
  2143. */
  2144. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2145. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2146. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2147. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2148. convertedColor.a = this.a;
  2149. return this;
  2150. };
  2151. /**
  2152. * Computes a new Color4 converted from the current one to gamma space
  2153. * @returns a new Color4 object
  2154. */
  2155. Color4.prototype.toGammaSpace = function () {
  2156. var convertedColor = new Color4();
  2157. this.toGammaSpaceToRef(convertedColor);
  2158. return convertedColor;
  2159. };
  2160. /**
  2161. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2162. * @param convertedColor defines the Color4 object where to store the gamma space version
  2163. * @returns the unmodified Color4
  2164. */
  2165. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2166. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2167. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2168. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2169. convertedColor.a = this.a;
  2170. return this;
  2171. };
  2172. // Statics
  2173. /**
  2174. * Creates a new Color4 from the string containing valid hexadecimal values
  2175. * @param hex defines a string containing valid hexadecimal values
  2176. * @returns a new Color4 object
  2177. */
  2178. Color4.FromHexString = function (hex) {
  2179. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2180. return new Color4(0.0, 0.0, 0.0, 0.0);
  2181. }
  2182. var r = parseInt(hex.substring(1, 3), 16);
  2183. var g = parseInt(hex.substring(3, 5), 16);
  2184. var b = parseInt(hex.substring(5, 7), 16);
  2185. var a = parseInt(hex.substring(7, 9), 16);
  2186. return Color4.FromInts(r, g, b, a);
  2187. };
  2188. /**
  2189. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2190. * @param left defines the start value
  2191. * @param right defines the end value
  2192. * @param amount defines the gradient factor
  2193. * @returns a new Color4 object
  2194. */
  2195. Color4.Lerp = function (left, right, amount) {
  2196. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2197. Color4.LerpToRef(left, right, amount, result);
  2198. return result;
  2199. };
  2200. /**
  2201. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2202. * @param left defines the start value
  2203. * @param right defines the end value
  2204. * @param amount defines the gradient factor
  2205. * @param result defines the Color4 object where to store data
  2206. */
  2207. Color4.LerpToRef = function (left, right, amount, result) {
  2208. result.r = left.r + (right.r - left.r) * amount;
  2209. result.g = left.g + (right.g - left.g) * amount;
  2210. result.b = left.b + (right.b - left.b) * amount;
  2211. result.a = left.a + (right.a - left.a) * amount;
  2212. };
  2213. /**
  2214. * Creates a new Color4 from the starting index element of the passed array
  2215. * @param array defines the source array to read from
  2216. * @param offset defines the offset in the source array
  2217. * @returns a new Color4 object
  2218. */
  2219. Color4.FromArray = function (array, offset) {
  2220. if (offset === void 0) { offset = 0; }
  2221. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2222. };
  2223. /**
  2224. * Creates a new Color3 from integer values (< 256)
  2225. * @param r defines the red component to read from (value between 0 and 255)
  2226. * @param g defines the green component to read from (value between 0 and 255)
  2227. * @param b defines the blue component to read from (value between 0 and 255)
  2228. * @param a defines the alpha component to read from (value between 0 and 255)
  2229. * @returns a new Color3 object
  2230. */
  2231. Color4.FromInts = function (r, g, b, a) {
  2232. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2233. };
  2234. /**
  2235. * Check the content of a given array and convert it to an array containing RGBA data
  2236. * If the original array was already containing count * 4 values then it is returned directly
  2237. * @param colors defines the array to check
  2238. * @param count defines the number of RGBA data to expect
  2239. * @returns an array containing count * 4 values (RGBA)
  2240. */
  2241. Color4.CheckColors4 = function (colors, count) {
  2242. // Check if color3 was used
  2243. if (colors.length === count * 3) {
  2244. var colors4 = [];
  2245. for (var index = 0; index < colors.length; index += 3) {
  2246. var newIndex = (index / 3) * 4;
  2247. colors4[newIndex] = colors[index];
  2248. colors4[newIndex + 1] = colors[index + 1];
  2249. colors4[newIndex + 2] = colors[index + 2];
  2250. colors4[newIndex + 3] = 1.0;
  2251. }
  2252. return colors4;
  2253. }
  2254. return colors;
  2255. };
  2256. return Color4;
  2257. }());
  2258. BABYLON.Color4 = Color4;
  2259. var Vector2 = /** @class */ (function () {
  2260. /**
  2261. * Creates a new Vector2 from the passed x and y coordinates.
  2262. */
  2263. function Vector2(x, y) {
  2264. this.x = x;
  2265. this.y = y;
  2266. }
  2267. /**
  2268. * Returns a string with the Vector2 coordinates.
  2269. */
  2270. Vector2.prototype.toString = function () {
  2271. return "{X: " + this.x + " Y:" + this.y + "}";
  2272. };
  2273. /**
  2274. * Returns the string "Vector2"
  2275. */
  2276. Vector2.prototype.getClassName = function () {
  2277. return "Vector2";
  2278. };
  2279. /**
  2280. * Returns the Vector2 hash code as a number.
  2281. */
  2282. Vector2.prototype.getHashCode = function () {
  2283. var hash = this.x || 0;
  2284. hash = (hash * 397) ^ (this.y || 0);
  2285. return hash;
  2286. };
  2287. // Operators
  2288. /**
  2289. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2290. * Returns the Vector2.
  2291. */
  2292. Vector2.prototype.toArray = function (array, index) {
  2293. if (index === void 0) { index = 0; }
  2294. array[index] = this.x;
  2295. array[index + 1] = this.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Returns a new array with 2 elements : the Vector2 coordinates.
  2300. */
  2301. Vector2.prototype.asArray = function () {
  2302. var result = new Array();
  2303. this.toArray(result, 0);
  2304. return result;
  2305. };
  2306. /**
  2307. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2308. * Returns the updated Vector2.
  2309. */
  2310. Vector2.prototype.copyFrom = function (source) {
  2311. this.x = source.x;
  2312. this.y = source.y;
  2313. return this;
  2314. };
  2315. /**
  2316. * Sets the Vector2 coordinates with the passed floats.
  2317. * Returns the updated Vector2.
  2318. */
  2319. Vector2.prototype.copyFromFloats = function (x, y) {
  2320. this.x = x;
  2321. this.y = y;
  2322. return this;
  2323. };
  2324. /**
  2325. * Sets the Vector2 coordinates with the passed floats.
  2326. * Returns the updated Vector2.
  2327. */
  2328. Vector2.prototype.set = function (x, y) {
  2329. return this.copyFromFloats(x, y);
  2330. };
  2331. /**
  2332. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2333. */
  2334. Vector2.prototype.add = function (otherVector) {
  2335. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2336. };
  2337. /**
  2338. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2339. * Returns the Vector2.
  2340. */
  2341. Vector2.prototype.addToRef = function (otherVector, result) {
  2342. result.x = this.x + otherVector.x;
  2343. result.y = this.y + otherVector.y;
  2344. return this;
  2345. };
  2346. /**
  2347. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2348. * Returns the updated Vector2.
  2349. */
  2350. Vector2.prototype.addInPlace = function (otherVector) {
  2351. this.x += otherVector.x;
  2352. this.y += otherVector.y;
  2353. return this;
  2354. };
  2355. /**
  2356. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2357. */
  2358. Vector2.prototype.addVector3 = function (otherVector) {
  2359. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2360. };
  2361. /**
  2362. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2363. */
  2364. Vector2.prototype.subtract = function (otherVector) {
  2365. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2366. };
  2367. /**
  2368. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2369. * Returns the Vector2.
  2370. */
  2371. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2372. result.x = this.x - otherVector.x;
  2373. result.y = this.y - otherVector.y;
  2374. return this;
  2375. };
  2376. /**
  2377. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2378. * Returns the updated Vector2.
  2379. */
  2380. Vector2.prototype.subtractInPlace = function (otherVector) {
  2381. this.x -= otherVector.x;
  2382. this.y -= otherVector.y;
  2383. return this;
  2384. };
  2385. /**
  2386. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2387. * Returns the updated Vector2.
  2388. */
  2389. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2390. this.x *= otherVector.x;
  2391. this.y *= otherVector.y;
  2392. return this;
  2393. };
  2394. /**
  2395. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2396. */
  2397. Vector2.prototype.multiply = function (otherVector) {
  2398. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2399. };
  2400. /**
  2401. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2402. * Returns the Vector2.
  2403. */
  2404. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2405. result.x = this.x * otherVector.x;
  2406. result.y = this.y * otherVector.y;
  2407. return this;
  2408. };
  2409. /**
  2410. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2411. */
  2412. Vector2.prototype.multiplyByFloats = function (x, y) {
  2413. return new Vector2(this.x * x, this.y * y);
  2414. };
  2415. /**
  2416. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2417. */
  2418. Vector2.prototype.divide = function (otherVector) {
  2419. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2420. };
  2421. /**
  2422. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2423. * Returns the Vector2.
  2424. */
  2425. Vector2.prototype.divideToRef = function (otherVector, result) {
  2426. result.x = this.x / otherVector.x;
  2427. result.y = this.y / otherVector.y;
  2428. return this;
  2429. };
  2430. /**
  2431. * Divides the current Vector3 coordinates by the passed ones.
  2432. * Returns the updated Vector3.
  2433. */
  2434. Vector2.prototype.divideInPlace = function (otherVector) {
  2435. return this.divideToRef(otherVector, this);
  2436. };
  2437. /**
  2438. * Returns a new Vector2 with current Vector2 negated coordinates.
  2439. */
  2440. Vector2.prototype.negate = function () {
  2441. return new Vector2(-this.x, -this.y);
  2442. };
  2443. /**
  2444. * Multiply the Vector2 coordinates by scale.
  2445. * Returns the updated Vector2.
  2446. */
  2447. Vector2.prototype.scaleInPlace = function (scale) {
  2448. this.x *= scale;
  2449. this.y *= scale;
  2450. return this;
  2451. };
  2452. /**
  2453. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2454. */
  2455. Vector2.prototype.scale = function (scale) {
  2456. var result = new Vector2(0, 0);
  2457. this.scaleToRef(scale, result);
  2458. return result;
  2459. };
  2460. /**
  2461. * Scale the current Vector2 values by a factor to a given Vector2
  2462. * @param scale defines the scale factor
  2463. * @param result defines the Vector2 object where to store the result
  2464. * @returns the unmodified current Vector2
  2465. */
  2466. Vector2.prototype.scaleToRef = function (scale, result) {
  2467. result.x = this.x * scale;
  2468. result.y = this.y * scale;
  2469. return this;
  2470. };
  2471. /**
  2472. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2473. * @param scale defines the scale factor
  2474. * @param result defines the Vector2 object where to store the result
  2475. * @returns the unmodified current Vector2
  2476. */
  2477. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2478. result.x += this.x * scale;
  2479. result.y += this.y * scale;
  2480. return this;
  2481. };
  2482. /**
  2483. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2484. */
  2485. Vector2.prototype.equals = function (otherVector) {
  2486. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2487. };
  2488. /**
  2489. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2490. */
  2491. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2492. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2493. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2494. };
  2495. // Properties
  2496. /**
  2497. * Returns the vector length (float).
  2498. */
  2499. Vector2.prototype.length = function () {
  2500. return Math.sqrt(this.x * this.x + this.y * this.y);
  2501. };
  2502. /**
  2503. * Returns the vector squared length (float);
  2504. */
  2505. Vector2.prototype.lengthSquared = function () {
  2506. return (this.x * this.x + this.y * this.y);
  2507. };
  2508. // Methods
  2509. /**
  2510. * Normalize the vector.
  2511. * Returns the updated Vector2.
  2512. */
  2513. Vector2.prototype.normalize = function () {
  2514. var len = this.length();
  2515. if (len === 0)
  2516. return this;
  2517. var num = 1.0 / len;
  2518. this.x *= num;
  2519. this.y *= num;
  2520. return this;
  2521. };
  2522. /**
  2523. * Returns a new Vector2 copied from the Vector2.
  2524. */
  2525. Vector2.prototype.clone = function () {
  2526. return new Vector2(this.x, this.y);
  2527. };
  2528. // Statics
  2529. /**
  2530. * Returns a new Vector2(0, 0)
  2531. */
  2532. Vector2.Zero = function () {
  2533. return new Vector2(0, 0);
  2534. };
  2535. /**
  2536. * Returns a new Vector2(1, 1)
  2537. */
  2538. Vector2.One = function () {
  2539. return new Vector2(1, 1);
  2540. };
  2541. /**
  2542. * Returns a new Vector2 set from the passed index element of the passed array.
  2543. */
  2544. Vector2.FromArray = function (array, offset) {
  2545. if (offset === void 0) { offset = 0; }
  2546. return new Vector2(array[offset], array[offset + 1]);
  2547. };
  2548. /**
  2549. * Sets "result" from the passed index element of the passed array.
  2550. */
  2551. Vector2.FromArrayToRef = function (array, offset, result) {
  2552. result.x = array[offset];
  2553. result.y = array[offset + 1];
  2554. };
  2555. /**
  2556. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2557. */
  2558. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2559. var squared = amount * amount;
  2560. var cubed = amount * squared;
  2561. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2562. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2563. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2564. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2565. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2566. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2567. return new Vector2(x, y);
  2568. };
  2569. /**
  2570. * 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".
  2571. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2572. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2573. */
  2574. Vector2.Clamp = function (value, min, max) {
  2575. var x = value.x;
  2576. x = (x > max.x) ? max.x : x;
  2577. x = (x < min.x) ? min.x : x;
  2578. var y = value.y;
  2579. y = (y > max.y) ? max.y : y;
  2580. y = (y < min.y) ? min.y : y;
  2581. return new Vector2(x, y);
  2582. };
  2583. /**
  2584. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2585. */
  2586. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2587. var squared = amount * amount;
  2588. var cubed = amount * squared;
  2589. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2590. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2591. var part3 = (cubed - (2.0 * squared)) + amount;
  2592. var part4 = cubed - squared;
  2593. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2594. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2595. return new Vector2(x, y);
  2596. };
  2597. /**
  2598. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2599. */
  2600. Vector2.Lerp = function (start, end, amount) {
  2601. var x = start.x + ((end.x - start.x) * amount);
  2602. var y = start.y + ((end.y - start.y) * amount);
  2603. return new Vector2(x, y);
  2604. };
  2605. /**
  2606. * Returns the dot product (float) of the vector "left" and the vector "right".
  2607. */
  2608. Vector2.Dot = function (left, right) {
  2609. return left.x * right.x + left.y * right.y;
  2610. };
  2611. /**
  2612. * Returns a new Vector2 equal to the normalized passed vector.
  2613. */
  2614. Vector2.Normalize = function (vector) {
  2615. var newVector = vector.clone();
  2616. newVector.normalize();
  2617. return newVector;
  2618. };
  2619. /**
  2620. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2621. */
  2622. Vector2.Minimize = function (left, right) {
  2623. var x = (left.x < right.x) ? left.x : right.x;
  2624. var y = (left.y < right.y) ? left.y : right.y;
  2625. return new Vector2(x, y);
  2626. };
  2627. /**
  2628. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2629. */
  2630. Vector2.Maximize = function (left, right) {
  2631. var x = (left.x > right.x) ? left.x : right.x;
  2632. var y = (left.y > right.y) ? left.y : right.y;
  2633. return new Vector2(x, y);
  2634. };
  2635. /**
  2636. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2637. */
  2638. Vector2.Transform = function (vector, transformation) {
  2639. var r = Vector2.Zero();
  2640. Vector2.TransformToRef(vector, transformation, r);
  2641. return r;
  2642. };
  2643. /**
  2644. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2645. */
  2646. Vector2.TransformToRef = function (vector, transformation, result) {
  2647. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2648. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2649. result.x = x;
  2650. result.y = y;
  2651. };
  2652. /**
  2653. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2654. */
  2655. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2656. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2657. var sign = a < 0 ? -1 : 1;
  2658. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2659. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2660. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2661. };
  2662. /**
  2663. * Returns the distance (float) between the vectors "value1" and "value2".
  2664. */
  2665. Vector2.Distance = function (value1, value2) {
  2666. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2667. };
  2668. /**
  2669. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2670. */
  2671. Vector2.DistanceSquared = function (value1, value2) {
  2672. var x = value1.x - value2.x;
  2673. var y = value1.y - value2.y;
  2674. return (x * x) + (y * y);
  2675. };
  2676. /**
  2677. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2678. */
  2679. Vector2.Center = function (value1, value2) {
  2680. var center = value1.add(value2);
  2681. center.scaleInPlace(0.5);
  2682. return center;
  2683. };
  2684. /**
  2685. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2686. */
  2687. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2688. var l2 = Vector2.DistanceSquared(segA, segB);
  2689. if (l2 === 0.0) {
  2690. return Vector2.Distance(p, segA);
  2691. }
  2692. var v = segB.subtract(segA);
  2693. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2694. var proj = segA.add(v.multiplyByFloats(t, t));
  2695. return Vector2.Distance(p, proj);
  2696. };
  2697. return Vector2;
  2698. }());
  2699. BABYLON.Vector2 = Vector2;
  2700. /**
  2701. * Classed used to store (x,y,z) vector representation
  2702. * A Vector3 is the main object used in 3D geometry
  2703. * It can represent etiher the coordinates of a point the space, either a direction
  2704. * Reminder: Babylon.js uses a left handed forward facing system
  2705. */
  2706. var Vector3 = /** @class */ (function () {
  2707. /**
  2708. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2709. * @param x defines the first coordinates (on X axis)
  2710. * @param y defines the second coordinates (on Y axis)
  2711. * @param z defines the third coordinates (on Z axis)
  2712. */
  2713. function Vector3(
  2714. /**
  2715. * Defines the first coordinates (on X axis)
  2716. */
  2717. x,
  2718. /**
  2719. * Defines the second coordinates (on Y axis)
  2720. */
  2721. y,
  2722. /**
  2723. * Defines the third coordinates (on Z axis)
  2724. */
  2725. z) {
  2726. this.x = x;
  2727. this.y = y;
  2728. this.z = z;
  2729. }
  2730. /**
  2731. * Creates a string representation of the Vector3
  2732. * @returns a string with the Vector3 coordinates.
  2733. */
  2734. Vector3.prototype.toString = function () {
  2735. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2736. };
  2737. /**
  2738. * Gets the class name
  2739. * @returns the string "Vector3"
  2740. */
  2741. Vector3.prototype.getClassName = function () {
  2742. return "Vector3";
  2743. };
  2744. /**
  2745. * Creates the Vector3 hash code
  2746. * @returns a number which tends to be unique between Vector3 instances
  2747. */
  2748. Vector3.prototype.getHashCode = function () {
  2749. var hash = this.x || 0;
  2750. hash = (hash * 397) ^ (this.y || 0);
  2751. hash = (hash * 397) ^ (this.z || 0);
  2752. return hash;
  2753. };
  2754. // Operators
  2755. /**
  2756. * Creates an array containing three elements : the coordinates of the Vector3
  2757. * @returns a new array of numbers
  2758. */
  2759. Vector3.prototype.asArray = function () {
  2760. var result = [];
  2761. this.toArray(result, 0);
  2762. return result;
  2763. };
  2764. /**
  2765. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2766. * @param array defines the destination array
  2767. * @param index defines the offset in the destination array
  2768. * @returns the current Vector3
  2769. */
  2770. Vector3.prototype.toArray = function (array, index) {
  2771. if (index === void 0) { index = 0; }
  2772. array[index] = this.x;
  2773. array[index + 1] = this.y;
  2774. array[index + 2] = this.z;
  2775. return this;
  2776. };
  2777. /**
  2778. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2779. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2780. */
  2781. Vector3.prototype.toQuaternion = function () {
  2782. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2783. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2784. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2785. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2786. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2787. var cosy = Math.cos(this.y * 0.5);
  2788. var siny = Math.sin(this.y * 0.5);
  2789. result.x = coszMinusx * siny;
  2790. result.y = -sinzMinusx * siny;
  2791. result.z = sinxPlusz * cosy;
  2792. result.w = cosxPlusz * cosy;
  2793. return result;
  2794. };
  2795. /**
  2796. * Adds the passed vector to the current Vector3
  2797. * @param otherVector defines the second operand
  2798. * @returns the current updated Vector3
  2799. */
  2800. Vector3.prototype.addInPlace = function (otherVector) {
  2801. this.x += otherVector.x;
  2802. this.y += otherVector.y;
  2803. this.z += otherVector.z;
  2804. return this;
  2805. };
  2806. /**
  2807. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2808. * @param otherVector defines the second operand
  2809. * @returns the resulting Vector3
  2810. */
  2811. Vector3.prototype.add = function (otherVector) {
  2812. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2813. };
  2814. /**
  2815. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2816. * @param otherVector defines the second operand
  2817. * @param result defines the Vector3 object where to store the result
  2818. * @returns the current Vector3
  2819. */
  2820. Vector3.prototype.addToRef = function (otherVector, result) {
  2821. result.x = this.x + otherVector.x;
  2822. result.y = this.y + otherVector.y;
  2823. result.z = this.z + otherVector.z;
  2824. return this;
  2825. };
  2826. /**
  2827. * Subtract the passed vector from the current Vector3
  2828. * @param otherVector defines the second operand
  2829. * @returns the current updated Vector3
  2830. */
  2831. Vector3.prototype.subtractInPlace = function (otherVector) {
  2832. this.x -= otherVector.x;
  2833. this.y -= otherVector.y;
  2834. this.z -= otherVector.z;
  2835. return this;
  2836. };
  2837. /**
  2838. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2839. * @param otherVector defines the second operand
  2840. * @returns the resulting Vector3
  2841. */
  2842. Vector3.prototype.subtract = function (otherVector) {
  2843. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2844. };
  2845. /**
  2846. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2847. * @param otherVector defines the second operand
  2848. * @param result defines the Vector3 object where to store the result
  2849. * @returns the current Vector3
  2850. */
  2851. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2852. result.x = this.x - otherVector.x;
  2853. result.y = this.y - otherVector.y;
  2854. result.z = this.z - otherVector.z;
  2855. return this;
  2856. };
  2857. /**
  2858. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2859. * @param x defines the x coordinate of the operand
  2860. * @param y defines the y coordinate of the operand
  2861. * @param z defines the z coordinate of the operand
  2862. * @returns the resulting Vector3
  2863. */
  2864. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2865. return new Vector3(this.x - x, this.y - y, this.z - z);
  2866. };
  2867. /**
  2868. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2869. * @param x defines the x coordinate of the operand
  2870. * @param y defines the y coordinate of the operand
  2871. * @param z defines the z coordinate of the operand
  2872. * @param result defines the Vector3 object where to store the result
  2873. * @returns the current Vector3
  2874. */
  2875. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2876. result.x = this.x - x;
  2877. result.y = this.y - y;
  2878. result.z = this.z - z;
  2879. return this;
  2880. };
  2881. /**
  2882. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2883. * @returns a new Vector3
  2884. */
  2885. Vector3.prototype.negate = function () {
  2886. return new Vector3(-this.x, -this.y, -this.z);
  2887. };
  2888. /**
  2889. * Multiplies the Vector3 coordinates by the float "scale"
  2890. * @param scale defines the multiplier factor
  2891. * @returns the current updated Vector3
  2892. */
  2893. Vector3.prototype.scaleInPlace = function (scale) {
  2894. this.x *= scale;
  2895. this.y *= scale;
  2896. this.z *= scale;
  2897. return this;
  2898. };
  2899. /**
  2900. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2901. * @param scale defines the multiplier factor
  2902. * @returns a new Vector3
  2903. */
  2904. Vector3.prototype.scale = function (scale) {
  2905. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2906. };
  2907. /**
  2908. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2909. * @param scale defines the multiplier factor
  2910. * @param result defines the Vector3 object where to store the result
  2911. * @returns the current Vector3
  2912. */
  2913. Vector3.prototype.scaleToRef = function (scale, result) {
  2914. result.x = this.x * scale;
  2915. result.y = this.y * scale;
  2916. result.z = this.z * scale;
  2917. return this;
  2918. };
  2919. /**
  2920. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2921. * @param scale defines the scale factor
  2922. * @param result defines the Vector3 object where to store the result
  2923. * @returns the unmodified current Vector3
  2924. */
  2925. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2926. result.x += this.x * scale;
  2927. result.y += this.y * scale;
  2928. result.z += this.z * scale;
  2929. return this;
  2930. };
  2931. /**
  2932. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2933. * @param otherVector defines the second operand
  2934. * @returns true if both vectors are equals
  2935. */
  2936. Vector3.prototype.equals = function (otherVector) {
  2937. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2938. };
  2939. /**
  2940. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2941. * @param otherVector defines the second operand
  2942. * @param epsilon defines the minimal distance to define values as equals
  2943. * @returns true if both vectors are distant less than epsilon
  2944. */
  2945. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2946. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2947. 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);
  2948. };
  2949. /**
  2950. * Returns true if the current Vector3 coordinates equals the passed floats
  2951. * @param x defines the x coordinate of the operand
  2952. * @param y defines the y coordinate of the operand
  2953. * @param z defines the z coordinate of the operand
  2954. * @returns true if both vectors are equals
  2955. */
  2956. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2957. return this.x === x && this.y === y && this.z === z;
  2958. };
  2959. /**
  2960. * Multiplies the current Vector3 coordinates by the passed ones
  2961. * @param otherVector defines the second operand
  2962. * @returns the current updated Vector3
  2963. */
  2964. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2965. this.x *= otherVector.x;
  2966. this.y *= otherVector.y;
  2967. this.z *= otherVector.z;
  2968. return this;
  2969. };
  2970. /**
  2971. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2972. * @param otherVector defines the second operand
  2973. * @returns the new Vector3
  2974. */
  2975. Vector3.prototype.multiply = function (otherVector) {
  2976. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2977. };
  2978. /**
  2979. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2980. * @param otherVector defines the second operand
  2981. * @param result defines the Vector3 object where to store the result
  2982. * @returns the current Vector3
  2983. */
  2984. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2985. result.x = this.x * otherVector.x;
  2986. result.y = this.y * otherVector.y;
  2987. result.z = this.z * otherVector.z;
  2988. return this;
  2989. };
  2990. /**
  2991. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2992. * @param x defines the x coordinate of the operand
  2993. * @param y defines the y coordinate of the operand
  2994. * @param z defines the z coordinate of the operand
  2995. * @returns the new Vector3
  2996. */
  2997. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2998. return new Vector3(this.x * x, this.y * y, this.z * z);
  2999. };
  3000. /**
  3001. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  3002. * @param otherVector defines the second operand
  3003. * @returns the new Vector3
  3004. */
  3005. Vector3.prototype.divide = function (otherVector) {
  3006. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3007. };
  3008. /**
  3009. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  3010. * @param otherVector defines the second operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.divideToRef = function (otherVector, result) {
  3015. result.x = this.x / otherVector.x;
  3016. result.y = this.y / otherVector.y;
  3017. result.z = this.z / otherVector.z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Divides the current Vector3 coordinates by the passed ones.
  3022. * @param otherVector defines the second operand
  3023. * @returns the current updated Vector3
  3024. */
  3025. Vector3.prototype.divideInPlace = function (otherVector) {
  3026. return this.divideToRef(otherVector, this);
  3027. };
  3028. /**
  3029. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3030. * @param other defines the second operand
  3031. * @returns the current updated Vector3
  3032. */
  3033. Vector3.prototype.minimizeInPlace = function (other) {
  3034. if (other.x < this.x)
  3035. this.x = other.x;
  3036. if (other.y < this.y)
  3037. this.y = other.y;
  3038. if (other.z < this.z)
  3039. this.z = other.z;
  3040. return this;
  3041. };
  3042. /**
  3043. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3044. * @param other defines the second operand
  3045. * @returns the current updated Vector3
  3046. */
  3047. Vector3.prototype.maximizeInPlace = function (other) {
  3048. if (other.x > this.x)
  3049. this.x = other.x;
  3050. if (other.y > this.y)
  3051. this.y = other.y;
  3052. if (other.z > this.z)
  3053. this.z = other.z;
  3054. return this;
  3055. };
  3056. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3057. /**
  3058. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3059. */
  3060. get: function () {
  3061. var absX = Math.abs(this.x);
  3062. var absY = Math.abs(this.y);
  3063. if (absX !== absY) {
  3064. return true;
  3065. }
  3066. var absZ = Math.abs(this.z);
  3067. if (absX !== absZ) {
  3068. return true;
  3069. }
  3070. if (absY !== absZ) {
  3071. return true;
  3072. }
  3073. return false;
  3074. },
  3075. enumerable: true,
  3076. configurable: true
  3077. });
  3078. // Properties
  3079. /**
  3080. * Gets the length of the Vector3
  3081. * @returns the length of the Vecto3
  3082. */
  3083. Vector3.prototype.length = function () {
  3084. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3085. };
  3086. /**
  3087. * Gets the squared length of the Vector3
  3088. * @returns squared length of the Vector3
  3089. */
  3090. Vector3.prototype.lengthSquared = function () {
  3091. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3092. };
  3093. /**
  3094. * Normalize the current Vector3.
  3095. * Please note that this is an in place operation.
  3096. * @returns the current updated Vector3
  3097. */
  3098. Vector3.prototype.normalize = function () {
  3099. var len = this.length();
  3100. if (len === 0 || len === 1.0)
  3101. return this;
  3102. var num = 1.0 / len;
  3103. this.x *= num;
  3104. this.y *= num;
  3105. this.z *= num;
  3106. return this;
  3107. };
  3108. /**
  3109. * Normalize the current Vector3 to a new vector
  3110. * @returns the new Vector3
  3111. */
  3112. Vector3.prototype.normalizeToNew = function () {
  3113. var normalized = new Vector3(0, 0, 0);
  3114. this.normalizeToRef(normalized);
  3115. return normalized;
  3116. };
  3117. /**
  3118. * Normalize the current Vector3 to the reference
  3119. * @param reference define the Vector3 to update
  3120. * @returns the updated Vector3
  3121. */
  3122. Vector3.prototype.normalizeToRef = function (reference) {
  3123. var len = this.length();
  3124. if (len === 0 || len === 1.0) {
  3125. reference.set(this.x, this.y, this.z);
  3126. return reference;
  3127. }
  3128. var scale = 1.0 / len;
  3129. this.scaleToRef(scale, reference);
  3130. return reference;
  3131. };
  3132. /**
  3133. * Creates a new Vector3 copied from the current Vector3
  3134. * @returns the new Vector3
  3135. */
  3136. Vector3.prototype.clone = function () {
  3137. return new Vector3(this.x, this.y, this.z);
  3138. };
  3139. /**
  3140. * Copies the passed vector coordinates to the current Vector3 ones
  3141. * @param source defines the source Vector3
  3142. * @returns the current updated Vector3
  3143. */
  3144. Vector3.prototype.copyFrom = function (source) {
  3145. this.x = source.x;
  3146. this.y = source.y;
  3147. this.z = source.z;
  3148. return this;
  3149. };
  3150. /**
  3151. * Copies the passed floats to the current Vector3 coordinates
  3152. * @param x defines the x coordinate of the operand
  3153. * @param y defines the y coordinate of the operand
  3154. * @param z defines the z coordinate of the operand
  3155. * @returns the current updated Vector3
  3156. */
  3157. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3158. this.x = x;
  3159. this.y = y;
  3160. this.z = z;
  3161. return this;
  3162. };
  3163. /**
  3164. * Copies the passed floats to the current Vector3 coordinates
  3165. * @param x defines the x coordinate of the operand
  3166. * @param y defines the y coordinate of the operand
  3167. * @param z defines the z coordinate of the operand
  3168. * @returns the current updated Vector3
  3169. */
  3170. Vector3.prototype.set = function (x, y, z) {
  3171. return this.copyFromFloats(x, y, z);
  3172. };
  3173. // Statics
  3174. /**
  3175. * Get the clip factor between two vectors
  3176. * @param vector0 defines the first operand
  3177. * @param vector1 defines the second operand
  3178. * @param axis defines the axis to use
  3179. * @param size defines the size along the axis
  3180. * @returns the clip factor
  3181. */
  3182. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3183. var d0 = Vector3.Dot(vector0, axis) - size;
  3184. var d1 = Vector3.Dot(vector1, axis) - size;
  3185. var s = d0 / (d0 - d1);
  3186. return s;
  3187. };
  3188. /**
  3189. * Get angle between two vectors
  3190. * @param vector0 angle between vector0 and vector1
  3191. * @param vector1 angle between vector0 and vector1
  3192. * @param normal direction of the normal
  3193. * @return the angle between vector0 and vector1
  3194. */
  3195. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3196. var v0 = vector0.clone().normalize();
  3197. var v1 = vector1.clone().normalize();
  3198. var dot = Vector3.Dot(v0, v1);
  3199. var n = Vector3.Cross(v0, v1);
  3200. if (Vector3.Dot(n, normal) > 0) {
  3201. return Math.acos(dot);
  3202. }
  3203. return -Math.acos(dot);
  3204. };
  3205. /**
  3206. * Returns a new Vector3 set from the index "offset" of the passed array
  3207. * @param array defines the source array
  3208. * @param offset defines the offset in the source array
  3209. * @returns the new Vector3
  3210. */
  3211. Vector3.FromArray = function (array, offset) {
  3212. if (!offset) {
  3213. offset = 0;
  3214. }
  3215. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3216. };
  3217. /**
  3218. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3219. * This function is deprecated. Use FromArray instead
  3220. * @param array defines the source array
  3221. * @param offset defines the offset in the source array
  3222. * @returns the new Vector3
  3223. */
  3224. Vector3.FromFloatArray = function (array, offset) {
  3225. return Vector3.FromArray(array, offset);
  3226. };
  3227. /**
  3228. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3229. * @param array defines the source array
  3230. * @param offset defines the offset in the source array
  3231. * @param result defines the Vector3 where to store the result
  3232. */
  3233. Vector3.FromArrayToRef = function (array, offset, result) {
  3234. result.x = array[offset];
  3235. result.y = array[offset + 1];
  3236. result.z = array[offset + 2];
  3237. };
  3238. /**
  3239. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3240. * This function is deprecated. Use FromArrayToRef instead.
  3241. * @param array defines the source array
  3242. * @param offset defines the offset in the source array
  3243. * @param result defines the Vector3 where to store the result
  3244. */
  3245. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3246. return Vector3.FromArrayToRef(array, offset, result);
  3247. };
  3248. /**
  3249. * Sets the passed vector "result" with the passed floats.
  3250. * @param x defines the x coordinate of the source
  3251. * @param y defines the y coordinate of the source
  3252. * @param z defines the z coordinate of the source
  3253. * @param result defines the Vector3 where to store the result
  3254. */
  3255. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3256. result.x = x;
  3257. result.y = y;
  3258. result.z = z;
  3259. };
  3260. /**
  3261. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3262. * @returns a new empty Vector3
  3263. */
  3264. Vector3.Zero = function () {
  3265. return new Vector3(0.0, 0.0, 0.0);
  3266. };
  3267. /**
  3268. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3269. * @returns a new unit Vector3
  3270. */
  3271. Vector3.One = function () {
  3272. return new Vector3(1.0, 1.0, 1.0);
  3273. };
  3274. /**
  3275. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3276. * @returns a new up Vector3
  3277. */
  3278. Vector3.Up = function () {
  3279. return new Vector3(0.0, 1.0, 0.0);
  3280. };
  3281. /**
  3282. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3283. * @returns a new forward Vector3
  3284. */
  3285. Vector3.Forward = function () {
  3286. return new Vector3(0.0, 0.0, 1.0);
  3287. };
  3288. /**
  3289. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3290. * @returns a new right Vector3
  3291. */
  3292. Vector3.Right = function () {
  3293. return new Vector3(1.0, 0.0, 0.0);
  3294. };
  3295. /**
  3296. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3297. * @returns a new left Vector3
  3298. */
  3299. Vector3.Left = function () {
  3300. return new Vector3(-1.0, 0.0, 0.0);
  3301. };
  3302. /**
  3303. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3304. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3305. * @param vector defines the Vector3 to transform
  3306. * @param transformation defines the transformation matrix
  3307. * @returns the transformed Vector3
  3308. */
  3309. Vector3.TransformCoordinates = function (vector, transformation) {
  3310. var result = Vector3.Zero();
  3311. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3312. return result;
  3313. };
  3314. /**
  3315. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3316. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3317. * @param vector defines the Vector3 to transform
  3318. * @param transformation defines the transformation matrix
  3319. * @param result defines the Vector3 where to store the result
  3320. */
  3321. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3322. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3323. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3324. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3325. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3326. result.x = x / w;
  3327. result.y = y / w;
  3328. result.z = z / w;
  3329. };
  3330. /**
  3331. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3332. * This method computes tranformed coordinates only, not transformed direction vectors
  3333. * @param x define the x coordinate of the source vector
  3334. * @param y define the y coordinate of the source vector
  3335. * @param z define the z coordinate of the source vector
  3336. * @param transformation defines the transformation matrix
  3337. * @param result defines the Vector3 where to store the result
  3338. */
  3339. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3340. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3341. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3342. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3343. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3344. result.x = rx / rw;
  3345. result.y = ry / rw;
  3346. result.z = rz / rw;
  3347. };
  3348. /**
  3349. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3350. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3351. * @param vector defines the Vector3 to transform
  3352. * @param transformation defines the transformation matrix
  3353. * @returns the new Vector3
  3354. */
  3355. Vector3.TransformNormal = function (vector, transformation) {
  3356. var result = Vector3.Zero();
  3357. Vector3.TransformNormalToRef(vector, transformation, result);
  3358. return result;
  3359. };
  3360. /**
  3361. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3362. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3363. * @param vector defines the Vector3 to transform
  3364. * @param transformation defines the transformation matrix
  3365. * @param result defines the Vector3 where to store the result
  3366. */
  3367. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3368. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3369. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3370. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3371. result.x = x;
  3372. result.y = y;
  3373. result.z = z;
  3374. };
  3375. /**
  3376. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3377. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3378. * @param x define the x coordinate of the source vector
  3379. * @param y define the y coordinate of the source vector
  3380. * @param z define the z coordinate of the source vector
  3381. * @param transformation defines the transformation matrix
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3385. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3386. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3387. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3388. };
  3389. /**
  3390. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3391. * @param value1 defines the first control point
  3392. * @param value2 defines the second control point
  3393. * @param value3 defines the third control point
  3394. * @param value4 defines the fourth control point
  3395. * @param amount defines the amount on the spline to use
  3396. * @returns the new Vector3
  3397. */
  3398. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3399. var squared = amount * amount;
  3400. var cubed = amount * squared;
  3401. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3402. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3403. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3404. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3405. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3406. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3407. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3408. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3409. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3410. return new Vector3(x, y, z);
  3411. };
  3412. /**
  3413. * 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"
  3414. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3415. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3416. * @param value defines the current value
  3417. * @param min defines the lower range value
  3418. * @param max defines the upper range value
  3419. * @returns the new Vector3
  3420. */
  3421. Vector3.Clamp = function (value, min, max) {
  3422. var x = value.x;
  3423. x = (x > max.x) ? max.x : x;
  3424. x = (x < min.x) ? min.x : x;
  3425. var y = value.y;
  3426. y = (y > max.y) ? max.y : y;
  3427. y = (y < min.y) ? min.y : y;
  3428. var z = value.z;
  3429. z = (z > max.z) ? max.z : z;
  3430. z = (z < min.z) ? min.z : z;
  3431. return new Vector3(x, y, z);
  3432. };
  3433. /**
  3434. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3435. * @param value1 defines the first control point
  3436. * @param tangent1 defines the first tangent vector
  3437. * @param value2 defines the second control point
  3438. * @param tangent2 defines the second tangent vector
  3439. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3440. * @returns the new Vector3
  3441. */
  3442. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3443. var squared = amount * amount;
  3444. var cubed = amount * squared;
  3445. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3446. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3447. var part3 = (cubed - (2.0 * squared)) + amount;
  3448. var part4 = cubed - squared;
  3449. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3450. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3451. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3452. return new Vector3(x, y, z);
  3453. };
  3454. /**
  3455. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3456. * @param start defines the start value
  3457. * @param end defines the end value
  3458. * @param amount max defines amount between both (between 0 and 1)
  3459. * @returns the new Vector3
  3460. */
  3461. Vector3.Lerp = function (start, end, amount) {
  3462. var result = new Vector3(0, 0, 0);
  3463. Vector3.LerpToRef(start, end, amount, result);
  3464. return result;
  3465. };
  3466. /**
  3467. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3468. * @param start defines the start value
  3469. * @param end defines the end value
  3470. * @param amount max defines amount between both (between 0 and 1)
  3471. * @param result defines the Vector3 where to store the result
  3472. */
  3473. Vector3.LerpToRef = function (start, end, amount, result) {
  3474. result.x = start.x + ((end.x - start.x) * amount);
  3475. result.y = start.y + ((end.y - start.y) * amount);
  3476. result.z = start.z + ((end.z - start.z) * amount);
  3477. };
  3478. /**
  3479. * Returns the dot product (float) between the vectors "left" and "right"
  3480. * @param left defines the left operand
  3481. * @param right defines the right operand
  3482. * @returns the dot product
  3483. */
  3484. Vector3.Dot = function (left, right) {
  3485. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3486. };
  3487. /**
  3488. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3489. * The cross product is then orthogonal to both "left" and "right"
  3490. * @param left defines the left operand
  3491. * @param right defines the right operand
  3492. * @returns the cross product
  3493. */
  3494. Vector3.Cross = function (left, right) {
  3495. var result = Vector3.Zero();
  3496. Vector3.CrossToRef(left, right, result);
  3497. return result;
  3498. };
  3499. /**
  3500. * Sets the passed vector "result" with the cross product of "left" and "right"
  3501. * The cross product is then orthogonal to both "left" and "right"
  3502. * @param left defines the left operand
  3503. * @param right defines the right operand
  3504. * @param result defines the Vector3 where to store the result
  3505. */
  3506. Vector3.CrossToRef = function (left, right, result) {
  3507. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3508. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3509. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3510. result.copyFrom(MathTmp.Vector3[0]);
  3511. };
  3512. /**
  3513. * Returns a new Vector3 as the normalization of the passed vector
  3514. * @param vector defines the Vector3 to normalize
  3515. * @returns the new Vector3
  3516. */
  3517. Vector3.Normalize = function (vector) {
  3518. var result = Vector3.Zero();
  3519. Vector3.NormalizeToRef(vector, result);
  3520. return result;
  3521. };
  3522. /**
  3523. * Sets the passed vector "result" with the normalization of the passed first vector
  3524. * @param vector defines the Vector3 to normalize
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.NormalizeToRef = function (vector, result) {
  3528. result.copyFrom(vector);
  3529. result.normalize();
  3530. };
  3531. /**
  3532. * Project a Vector3 onto screen space
  3533. * @param vector defines the Vector3 to project
  3534. * @param world defines the world matrix to use
  3535. * @param transform defines the transform (view x projection) matrix to use
  3536. * @param viewport defines the screen viewport to use
  3537. * @returns the new Vector3
  3538. */
  3539. Vector3.Project = function (vector, world, transform, viewport) {
  3540. var cw = viewport.width;
  3541. var ch = viewport.height;
  3542. var cx = viewport.x;
  3543. var cy = viewport.y;
  3544. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3545. 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);
  3546. var matrix = MathTmp.Matrix[0];
  3547. world.multiplyToRef(transform, matrix);
  3548. matrix.multiplyToRef(viewportMatrix, matrix);
  3549. return Vector3.TransformCoordinates(vector, matrix);
  3550. };
  3551. /**
  3552. * Unproject from screen space to object space
  3553. * @param source defines the screen space Vector3 to use
  3554. * @param viewportWidth defines the current width of the viewport
  3555. * @param viewportHeight defines the current height of the viewport
  3556. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3557. * @param transform defines the transform (view x projection) matrix to use
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3561. var matrix = MathTmp.Matrix[0];
  3562. world.multiplyToRef(transform, matrix);
  3563. matrix.invert();
  3564. source.x = source.x / viewportWidth * 2 - 1;
  3565. source.y = -(source.y / viewportHeight * 2 - 1);
  3566. var vector = Vector3.TransformCoordinates(source, matrix);
  3567. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3568. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3569. vector = vector.scale(1.0 / num);
  3570. }
  3571. return vector;
  3572. };
  3573. /**
  3574. * Unproject from screen space to object space
  3575. * @param source defines the screen space Vector3 to use
  3576. * @param viewportWidth defines the current width of the viewport
  3577. * @param viewportHeight defines the current height of the viewport
  3578. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3579. * @param view defines the view matrix to use
  3580. * @param projection defines the projection matrix to use
  3581. * @returns the new Vector3
  3582. */
  3583. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3584. var result = Vector3.Zero();
  3585. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3586. return result;
  3587. };
  3588. /**
  3589. * Unproject from screen space to object space
  3590. * @param source defines the screen space Vector3 to use
  3591. * @param viewportWidth defines the current width of the viewport
  3592. * @param viewportHeight defines the current height of the viewport
  3593. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3594. * @param view defines the view matrix to use
  3595. * @param projection defines the projection matrix to use
  3596. * @param result defines the Vector3 where to store the result
  3597. */
  3598. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3599. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3600. };
  3601. /**
  3602. * Unproject from screen space to object space
  3603. * @param sourceX defines the screen space x coordinate to use
  3604. * @param sourceY defines the screen space y coordinate to use
  3605. * @param sourceZ defines the screen space z coordinate to use
  3606. * @param viewportWidth defines the current width of the viewport
  3607. * @param viewportHeight defines the current height of the viewport
  3608. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3609. * @param view defines the view matrix to use
  3610. * @param projection defines the projection matrix to use
  3611. * @param result defines the Vector3 where to store the result
  3612. */
  3613. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3614. var matrix = MathTmp.Matrix[0];
  3615. world.multiplyToRef(view, matrix);
  3616. matrix.multiplyToRef(projection, matrix);
  3617. matrix.invert();
  3618. var screenSource = MathTmp.Vector3[0];
  3619. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3620. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3621. screenSource.z = 2 * sourceZ - 1.0;
  3622. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3623. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3624. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3625. result.scaleInPlace(1.0 / num);
  3626. }
  3627. };
  3628. /**
  3629. * Gets the minimal coordinate values between two Vector3
  3630. * @param left defines the first operand
  3631. * @param right defines the second operand
  3632. * @returns the new Vector3
  3633. */
  3634. Vector3.Minimize = function (left, right) {
  3635. var min = left.clone();
  3636. min.minimizeInPlace(right);
  3637. return min;
  3638. };
  3639. /**
  3640. * Gets the maximal coordinate values between two Vector3
  3641. * @param left defines the first operand
  3642. * @param right defines the second operand
  3643. * @returns the new Vector3
  3644. */
  3645. Vector3.Maximize = function (left, right) {
  3646. var max = left.clone();
  3647. max.maximizeInPlace(right);
  3648. return max;
  3649. };
  3650. /**
  3651. * Returns the distance between the vectors "value1" and "value2"
  3652. * @param value1 defines the first operand
  3653. * @param value2 defines the second operand
  3654. * @returns the distance
  3655. */
  3656. Vector3.Distance = function (value1, value2) {
  3657. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3658. };
  3659. /**
  3660. * Returns the squared distance between the vectors "value1" and "value2"
  3661. * @param value1 defines the first operand
  3662. * @param value2 defines the second operand
  3663. * @returns the squared distance
  3664. */
  3665. Vector3.DistanceSquared = function (value1, value2) {
  3666. var x = value1.x - value2.x;
  3667. var y = value1.y - value2.y;
  3668. var z = value1.z - value2.z;
  3669. return (x * x) + (y * y) + (z * z);
  3670. };
  3671. /**
  3672. * Returns a new Vector3 located at the center between "value1" and "value2"
  3673. * @param value1 defines the first operand
  3674. * @param value2 defines the second operand
  3675. * @returns the new Vector3
  3676. */
  3677. Vector3.Center = function (value1, value2) {
  3678. var center = value1.add(value2);
  3679. center.scaleInPlace(0.5);
  3680. return center;
  3681. };
  3682. /**
  3683. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3684. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3685. * to something in order to rotate it from its local system to the given target system
  3686. * Note: axis1, axis2 and axis3 are normalized during this operation
  3687. * @param axis1 defines the first axis
  3688. * @param axis2 defines the second axis
  3689. * @param axis3 defines the third axis
  3690. * @returns a new Vector3
  3691. */
  3692. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3693. var rotation = Vector3.Zero();
  3694. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3695. return rotation;
  3696. };
  3697. /**
  3698. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3699. * @param axis1 defines the first axis
  3700. * @param axis2 defines the second axis
  3701. * @param axis3 defines the third axis
  3702. * @param ref defines the Vector3 where to store the result
  3703. */
  3704. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3705. var quat = MathTmp.Quaternion[0];
  3706. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3707. quat.toEulerAnglesToRef(ref);
  3708. };
  3709. return Vector3;
  3710. }());
  3711. BABYLON.Vector3 = Vector3;
  3712. //Vector4 class created for EulerAngle class conversion to Quaternion
  3713. var Vector4 = /** @class */ (function () {
  3714. /**
  3715. * Creates a Vector4 object from the passed floats.
  3716. */
  3717. function Vector4(x, y, z, w) {
  3718. this.x = x;
  3719. this.y = y;
  3720. this.z = z;
  3721. this.w = w;
  3722. }
  3723. /**
  3724. * Returns the string with the Vector4 coordinates.
  3725. */
  3726. Vector4.prototype.toString = function () {
  3727. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3728. };
  3729. /**
  3730. * Returns the string "Vector4".
  3731. */
  3732. Vector4.prototype.getClassName = function () {
  3733. return "Vector4";
  3734. };
  3735. /**
  3736. * Returns the Vector4 hash code.
  3737. */
  3738. Vector4.prototype.getHashCode = function () {
  3739. var hash = this.x || 0;
  3740. hash = (hash * 397) ^ (this.y || 0);
  3741. hash = (hash * 397) ^ (this.z || 0);
  3742. hash = (hash * 397) ^ (this.w || 0);
  3743. return hash;
  3744. };
  3745. // Operators
  3746. /**
  3747. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3748. */
  3749. Vector4.prototype.asArray = function () {
  3750. var result = new Array();
  3751. this.toArray(result, 0);
  3752. return result;
  3753. };
  3754. /**
  3755. * Populates the passed array from the passed index with the Vector4 coordinates.
  3756. * Returns the Vector4.
  3757. */
  3758. Vector4.prototype.toArray = function (array, index) {
  3759. if (index === undefined) {
  3760. index = 0;
  3761. }
  3762. array[index] = this.x;
  3763. array[index + 1] = this.y;
  3764. array[index + 2] = this.z;
  3765. array[index + 3] = this.w;
  3766. return this;
  3767. };
  3768. /**
  3769. * Adds the passed vector to the current Vector4.
  3770. * Returns the updated Vector4.
  3771. */
  3772. Vector4.prototype.addInPlace = function (otherVector) {
  3773. this.x += otherVector.x;
  3774. this.y += otherVector.y;
  3775. this.z += otherVector.z;
  3776. this.w += otherVector.w;
  3777. return this;
  3778. };
  3779. /**
  3780. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3781. */
  3782. Vector4.prototype.add = function (otherVector) {
  3783. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3784. };
  3785. /**
  3786. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3787. * Returns the current Vector4.
  3788. */
  3789. Vector4.prototype.addToRef = function (otherVector, result) {
  3790. result.x = this.x + otherVector.x;
  3791. result.y = this.y + otherVector.y;
  3792. result.z = this.z + otherVector.z;
  3793. result.w = this.w + otherVector.w;
  3794. return this;
  3795. };
  3796. /**
  3797. * Subtract in place the passed vector from the current Vector4.
  3798. * Returns the updated Vector4.
  3799. */
  3800. Vector4.prototype.subtractInPlace = function (otherVector) {
  3801. this.x -= otherVector.x;
  3802. this.y -= otherVector.y;
  3803. this.z -= otherVector.z;
  3804. this.w -= otherVector.w;
  3805. return this;
  3806. };
  3807. /**
  3808. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3809. */
  3810. Vector4.prototype.subtract = function (otherVector) {
  3811. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3812. };
  3813. /**
  3814. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3815. * Returns the current Vector4.
  3816. */
  3817. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3818. result.x = this.x - otherVector.x;
  3819. result.y = this.y - otherVector.y;
  3820. result.z = this.z - otherVector.z;
  3821. result.w = this.w - otherVector.w;
  3822. return this;
  3823. };
  3824. /**
  3825. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3826. */
  3827. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3828. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3829. };
  3830. /**
  3831. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3832. * Returns the current Vector4.
  3833. */
  3834. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3835. result.x = this.x - x;
  3836. result.y = this.y - y;
  3837. result.z = this.z - z;
  3838. result.w = this.w - w;
  3839. return this;
  3840. };
  3841. /**
  3842. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3843. */
  3844. Vector4.prototype.negate = function () {
  3845. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3846. };
  3847. /**
  3848. * Multiplies the current Vector4 coordinates by scale (float).
  3849. * Returns the updated Vector4.
  3850. */
  3851. Vector4.prototype.scaleInPlace = function (scale) {
  3852. this.x *= scale;
  3853. this.y *= scale;
  3854. this.z *= scale;
  3855. this.w *= scale;
  3856. return this;
  3857. };
  3858. /**
  3859. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3860. */
  3861. Vector4.prototype.scale = function (scale) {
  3862. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3863. };
  3864. /**
  3865. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3866. * Returns the current Vector4.
  3867. */
  3868. Vector4.prototype.scaleToRef = function (scale, result) {
  3869. result.x = this.x * scale;
  3870. result.y = this.y * scale;
  3871. result.z = this.z * scale;
  3872. result.w = this.w * scale;
  3873. return this;
  3874. };
  3875. /**
  3876. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3877. * @param scale defines the scale factor
  3878. * @param result defines the Vector4 object where to store the result
  3879. * @returns the unmodified current Vector4
  3880. */
  3881. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3882. result.x += this.x * scale;
  3883. result.y += this.y * scale;
  3884. result.z += this.z * scale;
  3885. result.w += this.w * scale;
  3886. return this;
  3887. };
  3888. /**
  3889. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3890. */
  3891. Vector4.prototype.equals = function (otherVector) {
  3892. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3893. };
  3894. /**
  3895. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3896. */
  3897. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3898. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3899. return otherVector
  3900. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3901. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3902. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3903. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3904. };
  3905. /**
  3906. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3907. */
  3908. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3909. return this.x === x && this.y === y && this.z === z && this.w === w;
  3910. };
  3911. /**
  3912. * Multiplies in place the current Vector4 by the passed one.
  3913. * Returns the updated Vector4.
  3914. */
  3915. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3916. this.x *= otherVector.x;
  3917. this.y *= otherVector.y;
  3918. this.z *= otherVector.z;
  3919. this.w *= otherVector.w;
  3920. return this;
  3921. };
  3922. /**
  3923. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3924. */
  3925. Vector4.prototype.multiply = function (otherVector) {
  3926. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3927. };
  3928. /**
  3929. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3930. * Returns the current Vector4.
  3931. */
  3932. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3933. result.x = this.x * otherVector.x;
  3934. result.y = this.y * otherVector.y;
  3935. result.z = this.z * otherVector.z;
  3936. result.w = this.w * otherVector.w;
  3937. return this;
  3938. };
  3939. /**
  3940. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3941. */
  3942. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3943. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3944. };
  3945. /**
  3946. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3947. */
  3948. Vector4.prototype.divide = function (otherVector) {
  3949. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3950. };
  3951. /**
  3952. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3953. * Returns the current Vector4.
  3954. */
  3955. Vector4.prototype.divideToRef = function (otherVector, result) {
  3956. result.x = this.x / otherVector.x;
  3957. result.y = this.y / otherVector.y;
  3958. result.z = this.z / otherVector.z;
  3959. result.w = this.w / otherVector.w;
  3960. return this;
  3961. };
  3962. /**
  3963. * Divides the current Vector3 coordinates by the passed ones.
  3964. * @returns the updated Vector3.
  3965. */
  3966. Vector4.prototype.divideInPlace = function (otherVector) {
  3967. return this.divideToRef(otherVector, this);
  3968. };
  3969. /**
  3970. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3971. * @param other defines the second operand
  3972. * @returns the current updated Vector4
  3973. */
  3974. Vector4.prototype.minimizeInPlace = function (other) {
  3975. if (other.x < this.x)
  3976. this.x = other.x;
  3977. if (other.y < this.y)
  3978. this.y = other.y;
  3979. if (other.z < this.z)
  3980. this.z = other.z;
  3981. if (other.w < this.w)
  3982. this.w = other.w;
  3983. return this;
  3984. };
  3985. /**
  3986. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3987. * @param other defines the second operand
  3988. * @returns the current updated Vector4
  3989. */
  3990. Vector4.prototype.maximizeInPlace = function (other) {
  3991. if (other.x > this.x)
  3992. this.x = other.x;
  3993. if (other.y > this.y)
  3994. this.y = other.y;
  3995. if (other.z > this.z)
  3996. this.z = other.z;
  3997. if (other.w > this.w)
  3998. this.w = other.w;
  3999. return this;
  4000. };
  4001. // Properties
  4002. /**
  4003. * Returns the Vector4 length (float).
  4004. */
  4005. Vector4.prototype.length = function () {
  4006. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4007. };
  4008. /**
  4009. * Returns the Vector4 squared length (float).
  4010. */
  4011. Vector4.prototype.lengthSquared = function () {
  4012. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4013. };
  4014. // Methods
  4015. /**
  4016. * Normalizes in place the Vector4.
  4017. * Returns the updated Vector4.
  4018. */
  4019. Vector4.prototype.normalize = function () {
  4020. var len = this.length();
  4021. if (len === 0)
  4022. return this;
  4023. var num = 1.0 / len;
  4024. this.x *= num;
  4025. this.y *= num;
  4026. this.z *= num;
  4027. this.w *= num;
  4028. return this;
  4029. };
  4030. /**
  4031. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4032. */
  4033. Vector4.prototype.toVector3 = function () {
  4034. return new Vector3(this.x, this.y, this.z);
  4035. };
  4036. /**
  4037. * Returns a new Vector4 copied from the current one.
  4038. */
  4039. Vector4.prototype.clone = function () {
  4040. return new Vector4(this.x, this.y, this.z, this.w);
  4041. };
  4042. /**
  4043. * Updates the current Vector4 with the passed one coordinates.
  4044. * Returns the updated Vector4.
  4045. */
  4046. Vector4.prototype.copyFrom = function (source) {
  4047. this.x = source.x;
  4048. this.y = source.y;
  4049. this.z = source.z;
  4050. this.w = source.w;
  4051. return this;
  4052. };
  4053. /**
  4054. * Updates the current Vector4 coordinates with the passed floats.
  4055. * Returns the updated Vector4.
  4056. */
  4057. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4058. this.x = x;
  4059. this.y = y;
  4060. this.z = z;
  4061. this.w = w;
  4062. return this;
  4063. };
  4064. /**
  4065. * Updates the current Vector4 coordinates with the passed floats.
  4066. * Returns the updated Vector4.
  4067. */
  4068. Vector4.prototype.set = function (x, y, z, w) {
  4069. return this.copyFromFloats(x, y, z, w);
  4070. };
  4071. // Statics
  4072. /**
  4073. * Returns a new Vector4 set from the starting index of the passed array.
  4074. */
  4075. Vector4.FromArray = function (array, offset) {
  4076. if (!offset) {
  4077. offset = 0;
  4078. }
  4079. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4080. };
  4081. /**
  4082. * Updates the passed vector "result" from the starting index of the passed array.
  4083. */
  4084. Vector4.FromArrayToRef = function (array, offset, result) {
  4085. result.x = array[offset];
  4086. result.y = array[offset + 1];
  4087. result.z = array[offset + 2];
  4088. result.w = array[offset + 3];
  4089. };
  4090. /**
  4091. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4092. */
  4093. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4094. Vector4.FromArrayToRef(array, offset, result);
  4095. };
  4096. /**
  4097. * Updates the passed vector "result" coordinates from the passed floats.
  4098. */
  4099. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4100. result.x = x;
  4101. result.y = y;
  4102. result.z = z;
  4103. result.w = w;
  4104. };
  4105. /**
  4106. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4107. */
  4108. Vector4.Zero = function () {
  4109. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4110. };
  4111. /**
  4112. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4113. */
  4114. Vector4.One = function () {
  4115. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4116. };
  4117. /**
  4118. * Returns a new normalized Vector4 from the passed one.
  4119. */
  4120. Vector4.Normalize = function (vector) {
  4121. var result = Vector4.Zero();
  4122. Vector4.NormalizeToRef(vector, result);
  4123. return result;
  4124. };
  4125. /**
  4126. * Updates the passed vector "result" from the normalization of the passed one.
  4127. */
  4128. Vector4.NormalizeToRef = function (vector, result) {
  4129. result.copyFrom(vector);
  4130. result.normalize();
  4131. };
  4132. Vector4.Minimize = function (left, right) {
  4133. var min = left.clone();
  4134. min.minimizeInPlace(right);
  4135. return min;
  4136. };
  4137. Vector4.Maximize = function (left, right) {
  4138. var max = left.clone();
  4139. max.maximizeInPlace(right);
  4140. return max;
  4141. };
  4142. /**
  4143. * Returns the distance (float) between the vectors "value1" and "value2".
  4144. */
  4145. Vector4.Distance = function (value1, value2) {
  4146. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4147. };
  4148. /**
  4149. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4150. */
  4151. Vector4.DistanceSquared = function (value1, value2) {
  4152. var x = value1.x - value2.x;
  4153. var y = value1.y - value2.y;
  4154. var z = value1.z - value2.z;
  4155. var w = value1.w - value2.w;
  4156. return (x * x) + (y * y) + (z * z) + (w * w);
  4157. };
  4158. /**
  4159. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4160. */
  4161. Vector4.Center = function (value1, value2) {
  4162. var center = value1.add(value2);
  4163. center.scaleInPlace(0.5);
  4164. return center;
  4165. };
  4166. /**
  4167. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4168. * This methods computes transformed normalized direction vectors only.
  4169. */
  4170. Vector4.TransformNormal = function (vector, transformation) {
  4171. var result = Vector4.Zero();
  4172. Vector4.TransformNormalToRef(vector, transformation, result);
  4173. return result;
  4174. };
  4175. /**
  4176. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4177. * This methods computes transformed normalized direction vectors only.
  4178. */
  4179. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4180. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4181. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4182. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4183. result.x = x;
  4184. result.y = y;
  4185. result.z = z;
  4186. result.w = vector.w;
  4187. };
  4188. /**
  4189. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4190. * This methods computes transformed normalized direction vectors only.
  4191. */
  4192. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4193. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4194. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4195. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4196. result.w = w;
  4197. };
  4198. return Vector4;
  4199. }());
  4200. BABYLON.Vector4 = Vector4;
  4201. var Size = /** @class */ (function () {
  4202. /**
  4203. * Creates a Size object from the passed width and height (floats).
  4204. */
  4205. function Size(width, height) {
  4206. this.width = width;
  4207. this.height = height;
  4208. }
  4209. // Returns a string with the Size width and height.
  4210. Size.prototype.toString = function () {
  4211. return "{W: " + this.width + ", H: " + this.height + "}";
  4212. };
  4213. /**
  4214. * Returns the string "Size"
  4215. */
  4216. Size.prototype.getClassName = function () {
  4217. return "Size";
  4218. };
  4219. /**
  4220. * Returns the Size hash code.
  4221. */
  4222. Size.prototype.getHashCode = function () {
  4223. var hash = this.width || 0;
  4224. hash = (hash * 397) ^ (this.height || 0);
  4225. return hash;
  4226. };
  4227. /**
  4228. * Updates the current size from the passed one.
  4229. * Returns the updated Size.
  4230. */
  4231. Size.prototype.copyFrom = function (src) {
  4232. this.width = src.width;
  4233. this.height = src.height;
  4234. };
  4235. /**
  4236. * Updates in place the current Size from the passed floats.
  4237. * Returns the updated Size.
  4238. */
  4239. Size.prototype.copyFromFloats = function (width, height) {
  4240. this.width = width;
  4241. this.height = height;
  4242. return this;
  4243. };
  4244. /**
  4245. * Updates in place the current Size from the passed floats.
  4246. * Returns the updated Size.
  4247. */
  4248. Size.prototype.set = function (width, height) {
  4249. return this.copyFromFloats(width, height);
  4250. };
  4251. /**
  4252. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4253. */
  4254. Size.prototype.multiplyByFloats = function (w, h) {
  4255. return new Size(this.width * w, this.height * h);
  4256. };
  4257. /**
  4258. * Returns a new Size copied from the passed one.
  4259. */
  4260. Size.prototype.clone = function () {
  4261. return new Size(this.width, this.height);
  4262. };
  4263. /**
  4264. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4265. */
  4266. Size.prototype.equals = function (other) {
  4267. if (!other) {
  4268. return false;
  4269. }
  4270. return (this.width === other.width) && (this.height === other.height);
  4271. };
  4272. Object.defineProperty(Size.prototype, "surface", {
  4273. /**
  4274. * Returns the surface of the Size : width * height (float).
  4275. */
  4276. get: function () {
  4277. return this.width * this.height;
  4278. },
  4279. enumerable: true,
  4280. configurable: true
  4281. });
  4282. /**
  4283. * Returns a new Size set to (0.0, 0.0)
  4284. */
  4285. Size.Zero = function () {
  4286. return new Size(0.0, 0.0);
  4287. };
  4288. /**
  4289. * Returns a new Size set as the addition result of the current Size and the passed one.
  4290. */
  4291. Size.prototype.add = function (otherSize) {
  4292. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4293. return r;
  4294. };
  4295. /**
  4296. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4297. */
  4298. Size.prototype.subtract = function (otherSize) {
  4299. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4300. return r;
  4301. };
  4302. /**
  4303. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4304. */
  4305. Size.Lerp = function (start, end, amount) {
  4306. var w = start.width + ((end.width - start.width) * amount);
  4307. var h = start.height + ((end.height - start.height) * amount);
  4308. return new Size(w, h);
  4309. };
  4310. return Size;
  4311. }());
  4312. BABYLON.Size = Size;
  4313. var Quaternion = /** @class */ (function () {
  4314. /**
  4315. * Creates a new Quaternion from the passed floats.
  4316. */
  4317. function Quaternion(x, y, z, w) {
  4318. if (x === void 0) { x = 0.0; }
  4319. if (y === void 0) { y = 0.0; }
  4320. if (z === void 0) { z = 0.0; }
  4321. if (w === void 0) { w = 1.0; }
  4322. this.x = x;
  4323. this.y = y;
  4324. this.z = z;
  4325. this.w = w;
  4326. }
  4327. /**
  4328. * Returns a string with the Quaternion coordinates.
  4329. */
  4330. Quaternion.prototype.toString = function () {
  4331. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4332. };
  4333. /**
  4334. * Returns the string "Quaternion".
  4335. */
  4336. Quaternion.prototype.getClassName = function () {
  4337. return "Quaternion";
  4338. };
  4339. /**
  4340. * Returns the Quaternion hash code.
  4341. */
  4342. Quaternion.prototype.getHashCode = function () {
  4343. var hash = this.x || 0;
  4344. hash = (hash * 397) ^ (this.y || 0);
  4345. hash = (hash * 397) ^ (this.z || 0);
  4346. hash = (hash * 397) ^ (this.w || 0);
  4347. return hash;
  4348. };
  4349. /**
  4350. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4351. */
  4352. Quaternion.prototype.asArray = function () {
  4353. return [this.x, this.y, this.z, this.w];
  4354. };
  4355. /**
  4356. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4357. */
  4358. Quaternion.prototype.equals = function (otherQuaternion) {
  4359. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4360. };
  4361. /**
  4362. * Returns a new Quaternion copied from the current one.
  4363. */
  4364. Quaternion.prototype.clone = function () {
  4365. return new Quaternion(this.x, this.y, this.z, this.w);
  4366. };
  4367. /**
  4368. * Updates the current Quaternion from the passed one coordinates.
  4369. * Returns the updated Quaterion.
  4370. */
  4371. Quaternion.prototype.copyFrom = function (other) {
  4372. this.x = other.x;
  4373. this.y = other.y;
  4374. this.z = other.z;
  4375. this.w = other.w;
  4376. return this;
  4377. };
  4378. /**
  4379. * Updates the current Quaternion from the passed float coordinates.
  4380. * Returns the updated Quaterion.
  4381. */
  4382. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4383. this.x = x;
  4384. this.y = y;
  4385. this.z = z;
  4386. this.w = w;
  4387. return this;
  4388. };
  4389. /**
  4390. * Updates the current Quaternion from the passed float coordinates.
  4391. * Returns the updated Quaterion.
  4392. */
  4393. Quaternion.prototype.set = function (x, y, z, w) {
  4394. return this.copyFromFloats(x, y, z, w);
  4395. };
  4396. /**
  4397. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4398. */
  4399. Quaternion.prototype.add = function (other) {
  4400. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4401. };
  4402. /**
  4403. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4404. */
  4405. Quaternion.prototype.subtract = function (other) {
  4406. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4407. };
  4408. /**
  4409. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4410. */
  4411. Quaternion.prototype.scale = function (value) {
  4412. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4413. };
  4414. /**
  4415. * Scale the current Quaternion values by a factor to a given Quaternion
  4416. * @param scale defines the scale factor
  4417. * @param result defines the Quaternion object where to store the result
  4418. * @returns the unmodified current Quaternion
  4419. */
  4420. Quaternion.prototype.scaleToRef = function (scale, result) {
  4421. result.x = this.x * scale;
  4422. result.y = this.y * scale;
  4423. result.z = this.z * scale;
  4424. result.w = this.w * scale;
  4425. return this;
  4426. };
  4427. /**
  4428. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4429. * @param scale defines the scale factor
  4430. * @param result defines the Quaternion object where to store the result
  4431. * @returns the unmodified current Quaternion
  4432. */
  4433. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4434. result.x += this.x * scale;
  4435. result.y += this.y * scale;
  4436. result.z += this.z * scale;
  4437. result.w += this.w * scale;
  4438. return this;
  4439. };
  4440. /**
  4441. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4442. */
  4443. Quaternion.prototype.multiply = function (q1) {
  4444. var result = new Quaternion(0, 0, 0, 1.0);
  4445. this.multiplyToRef(q1, result);
  4446. return result;
  4447. };
  4448. /**
  4449. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4450. * Returns the current Quaternion.
  4451. */
  4452. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4453. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4454. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4455. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4456. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4457. result.copyFromFloats(x, y, z, w);
  4458. return this;
  4459. };
  4460. /**
  4461. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4462. * Returns the updated Quaternion.
  4463. */
  4464. Quaternion.prototype.multiplyInPlace = function (q1) {
  4465. this.multiplyToRef(q1, this);
  4466. return this;
  4467. };
  4468. /**
  4469. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4470. * Returns the current Quaternion.
  4471. */
  4472. Quaternion.prototype.conjugateToRef = function (ref) {
  4473. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4474. return this;
  4475. };
  4476. /**
  4477. * Conjugates in place the current Quaternion.
  4478. * Returns the updated Quaternion.
  4479. */
  4480. Quaternion.prototype.conjugateInPlace = function () {
  4481. this.x *= -1;
  4482. this.y *= -1;
  4483. this.z *= -1;
  4484. return this;
  4485. };
  4486. /**
  4487. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4488. */
  4489. Quaternion.prototype.conjugate = function () {
  4490. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4491. return result;
  4492. };
  4493. /**
  4494. * Returns the Quaternion length (float).
  4495. */
  4496. Quaternion.prototype.length = function () {
  4497. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4498. };
  4499. /**
  4500. * Normalize in place the current Quaternion.
  4501. * Returns the updated Quaternion.
  4502. */
  4503. Quaternion.prototype.normalize = function () {
  4504. var length = 1.0 / this.length();
  4505. this.x *= length;
  4506. this.y *= length;
  4507. this.z *= length;
  4508. this.w *= length;
  4509. return this;
  4510. };
  4511. /**
  4512. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4513. * @param order is a reserved parameter and is ignore for now
  4514. * @returns the new Vector3
  4515. */
  4516. Quaternion.prototype.toEulerAngles = function (order) {
  4517. if (order === void 0) { order = "YZX"; }
  4518. var result = Vector3.Zero();
  4519. this.toEulerAnglesToRef(result, order);
  4520. return result;
  4521. };
  4522. /**
  4523. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4524. * @param result defines the vector which will be filled with the Euler angles
  4525. * @param order is a reserved parameter and is ignore for now
  4526. * @returns the current Quaternion
  4527. */
  4528. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4529. if (order === void 0) { order = "YZX"; }
  4530. var qz = this.z;
  4531. var qx = this.x;
  4532. var qy = this.y;
  4533. var qw = this.w;
  4534. var sqw = qw * qw;
  4535. var sqz = qz * qz;
  4536. var sqx = qx * qx;
  4537. var sqy = qy * qy;
  4538. var zAxisY = qy * qz - qx * qw;
  4539. var limit = .4999999;
  4540. if (zAxisY < -limit) {
  4541. result.y = 2 * Math.atan2(qy, qw);
  4542. result.x = Math.PI / 2;
  4543. result.z = 0;
  4544. }
  4545. else if (zAxisY > limit) {
  4546. result.y = 2 * Math.atan2(qy, qw);
  4547. result.x = -Math.PI / 2;
  4548. result.z = 0;
  4549. }
  4550. else {
  4551. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4552. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4553. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4554. }
  4555. return this;
  4556. };
  4557. /**
  4558. * Updates the passed rotation matrix with the current Quaternion values.
  4559. * Returns the current Quaternion.
  4560. */
  4561. Quaternion.prototype.toRotationMatrix = function (result) {
  4562. var xx = this.x * this.x;
  4563. var yy = this.y * this.y;
  4564. var zz = this.z * this.z;
  4565. var xy = this.x * this.y;
  4566. var zw = this.z * this.w;
  4567. var zx = this.z * this.x;
  4568. var yw = this.y * this.w;
  4569. var yz = this.y * this.z;
  4570. var xw = this.x * this.w;
  4571. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4572. result.m[1] = 2.0 * (xy + zw);
  4573. result.m[2] = 2.0 * (zx - yw);
  4574. result.m[3] = 0;
  4575. result.m[4] = 2.0 * (xy - zw);
  4576. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4577. result.m[6] = 2.0 * (yz + xw);
  4578. result.m[7] = 0;
  4579. result.m[8] = 2.0 * (zx + yw);
  4580. result.m[9] = 2.0 * (yz - xw);
  4581. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4582. result.m[11] = 0;
  4583. result.m[12] = 0;
  4584. result.m[13] = 0;
  4585. result.m[14] = 0;
  4586. result.m[15] = 1.0;
  4587. result._markAsUpdated();
  4588. return this;
  4589. };
  4590. /**
  4591. * Updates the current Quaternion from the passed rotation matrix values.
  4592. * Returns the updated Quaternion.
  4593. */
  4594. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4595. Quaternion.FromRotationMatrixToRef(matrix, this);
  4596. return this;
  4597. };
  4598. // Statics
  4599. /**
  4600. * Returns a new Quaternion set from the passed rotation matrix values.
  4601. */
  4602. Quaternion.FromRotationMatrix = function (matrix) {
  4603. var result = new Quaternion();
  4604. Quaternion.FromRotationMatrixToRef(matrix, result);
  4605. return result;
  4606. };
  4607. /**
  4608. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4609. */
  4610. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4611. var data = matrix.m;
  4612. var m11 = data[0], m12 = data[4], m13 = data[8];
  4613. var m21 = data[1], m22 = data[5], m23 = data[9];
  4614. var m31 = data[2], m32 = data[6], m33 = data[10];
  4615. var trace = m11 + m22 + m33;
  4616. var s;
  4617. if (trace > 0) {
  4618. s = 0.5 / Math.sqrt(trace + 1.0);
  4619. result.w = 0.25 / s;
  4620. result.x = (m32 - m23) * s;
  4621. result.y = (m13 - m31) * s;
  4622. result.z = (m21 - m12) * s;
  4623. }
  4624. else if (m11 > m22 && m11 > m33) {
  4625. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4626. result.w = (m32 - m23) / s;
  4627. result.x = 0.25 * s;
  4628. result.y = (m12 + m21) / s;
  4629. result.z = (m13 + m31) / s;
  4630. }
  4631. else if (m22 > m33) {
  4632. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4633. result.w = (m13 - m31) / s;
  4634. result.x = (m12 + m21) / s;
  4635. result.y = 0.25 * s;
  4636. result.z = (m23 + m32) / s;
  4637. }
  4638. else {
  4639. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4640. result.w = (m21 - m12) / s;
  4641. result.x = (m13 + m31) / s;
  4642. result.y = (m23 + m32) / s;
  4643. result.z = 0.25 * s;
  4644. }
  4645. };
  4646. /**
  4647. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4648. */
  4649. Quaternion.Zero = function () {
  4650. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4651. };
  4652. /**
  4653. * Returns a new Quaternion as the inverted current Quaternion.
  4654. */
  4655. Quaternion.Inverse = function (q) {
  4656. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4657. };
  4658. /**
  4659. * Returns the identity Quaternion.
  4660. */
  4661. Quaternion.Identity = function () {
  4662. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4663. };
  4664. Quaternion.IsIdentity = function (quaternion) {
  4665. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4666. };
  4667. /**
  4668. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4669. */
  4670. Quaternion.RotationAxis = function (axis, angle) {
  4671. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4672. };
  4673. /**
  4674. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4675. */
  4676. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4677. var sin = Math.sin(angle / 2);
  4678. axis.normalize();
  4679. result.w = Math.cos(angle / 2);
  4680. result.x = axis.x * sin;
  4681. result.y = axis.y * sin;
  4682. result.z = axis.z * sin;
  4683. return result;
  4684. };
  4685. /**
  4686. * Retuns a new Quaternion set from the starting index of the passed array.
  4687. */
  4688. Quaternion.FromArray = function (array, offset) {
  4689. if (!offset) {
  4690. offset = 0;
  4691. }
  4692. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4693. };
  4694. /**
  4695. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4696. */
  4697. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4698. var q = new Quaternion();
  4699. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4700. return q;
  4701. };
  4702. /**
  4703. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4704. */
  4705. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4706. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4707. var halfRoll = roll * 0.5;
  4708. var halfPitch = pitch * 0.5;
  4709. var halfYaw = yaw * 0.5;
  4710. var sinRoll = Math.sin(halfRoll);
  4711. var cosRoll = Math.cos(halfRoll);
  4712. var sinPitch = Math.sin(halfPitch);
  4713. var cosPitch = Math.cos(halfPitch);
  4714. var sinYaw = Math.sin(halfYaw);
  4715. var cosYaw = Math.cos(halfYaw);
  4716. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4717. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4718. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4719. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4720. };
  4721. /**
  4722. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4723. */
  4724. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4725. var result = new Quaternion();
  4726. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4727. return result;
  4728. };
  4729. /**
  4730. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4731. */
  4732. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4733. // Produces a quaternion from Euler angles in the z-x-z orientation
  4734. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4735. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4736. var halfBeta = beta * 0.5;
  4737. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4738. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4739. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4740. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4741. };
  4742. /**
  4743. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4744. * cf to Vector3.RotationFromAxis() documentation.
  4745. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4746. */
  4747. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4748. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4749. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4750. return quat;
  4751. };
  4752. /**
  4753. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4754. * cf to Vector3.RotationFromAxis() documentation.
  4755. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4756. */
  4757. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4758. var rotMat = MathTmp.Matrix[0];
  4759. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4760. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4761. };
  4762. Quaternion.Slerp = function (left, right, amount) {
  4763. var result = Quaternion.Identity();
  4764. Quaternion.SlerpToRef(left, right, amount, result);
  4765. return result;
  4766. };
  4767. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4768. var num2;
  4769. var num3;
  4770. var num = amount;
  4771. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4772. var flag = false;
  4773. if (num4 < 0) {
  4774. flag = true;
  4775. num4 = -num4;
  4776. }
  4777. if (num4 > 0.999999) {
  4778. num3 = 1 - num;
  4779. num2 = flag ? -num : num;
  4780. }
  4781. else {
  4782. var num5 = Math.acos(num4);
  4783. var num6 = (1.0 / Math.sin(num5));
  4784. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4785. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4786. }
  4787. result.x = (num3 * left.x) + (num2 * right.x);
  4788. result.y = (num3 * left.y) + (num2 * right.y);
  4789. result.z = (num3 * left.z) + (num2 * right.z);
  4790. result.w = (num3 * left.w) + (num2 * right.w);
  4791. };
  4792. /**
  4793. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4794. */
  4795. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4796. var squared = amount * amount;
  4797. var cubed = amount * squared;
  4798. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4799. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4800. var part3 = (cubed - (2.0 * squared)) + amount;
  4801. var part4 = cubed - squared;
  4802. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4803. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4804. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4805. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4806. return new Quaternion(x, y, z, w);
  4807. };
  4808. return Quaternion;
  4809. }());
  4810. BABYLON.Quaternion = Quaternion;
  4811. var Matrix = /** @class */ (function () {
  4812. function Matrix() {
  4813. this._isIdentity = false;
  4814. this._isIdentityDirty = true;
  4815. this.m = new Float32Array(16);
  4816. this._markAsUpdated();
  4817. }
  4818. Matrix.prototype._markAsUpdated = function () {
  4819. this.updateFlag = Matrix._updateFlagSeed++;
  4820. this._isIdentityDirty = true;
  4821. };
  4822. // Properties
  4823. /**
  4824. * Boolean : True is the matrix is the identity matrix
  4825. */
  4826. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4827. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4828. if (this._isIdentityDirty) {
  4829. this._isIdentityDirty = false;
  4830. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4831. this._isIdentity = false;
  4832. }
  4833. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4834. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4835. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4836. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4837. this._isIdentity = false;
  4838. }
  4839. else {
  4840. this._isIdentity = true;
  4841. }
  4842. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4843. this._isIdentity = false;
  4844. }
  4845. }
  4846. return this._isIdentity;
  4847. };
  4848. /**
  4849. * Returns the matrix determinant (float).
  4850. */
  4851. Matrix.prototype.determinant = function () {
  4852. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4853. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4854. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4855. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4856. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4857. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4858. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4859. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4860. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4861. };
  4862. // Methods
  4863. /**
  4864. * Returns the matrix underlying array.
  4865. */
  4866. Matrix.prototype.toArray = function () {
  4867. return this.m;
  4868. };
  4869. /**
  4870. * Returns the matrix underlying array.
  4871. */
  4872. Matrix.prototype.asArray = function () {
  4873. return this.toArray();
  4874. };
  4875. /**
  4876. * Inverts in place the Matrix.
  4877. * Returns the Matrix inverted.
  4878. */
  4879. Matrix.prototype.invert = function () {
  4880. this.invertToRef(this);
  4881. return this;
  4882. };
  4883. /**
  4884. * Sets all the matrix elements to zero.
  4885. * Returns the Matrix.
  4886. */
  4887. Matrix.prototype.reset = function () {
  4888. for (var index = 0; index < 16; index++) {
  4889. this.m[index] = 0.0;
  4890. }
  4891. this._markAsUpdated();
  4892. return this;
  4893. };
  4894. /**
  4895. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4896. */
  4897. Matrix.prototype.add = function (other) {
  4898. var result = new Matrix();
  4899. this.addToRef(other, result);
  4900. return result;
  4901. };
  4902. /**
  4903. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4904. * Returns the Matrix.
  4905. */
  4906. Matrix.prototype.addToRef = function (other, result) {
  4907. for (var index = 0; index < 16; index++) {
  4908. result.m[index] = this.m[index] + other.m[index];
  4909. }
  4910. result._markAsUpdated();
  4911. return this;
  4912. };
  4913. /**
  4914. * Adds in place the passed matrix to the current Matrix.
  4915. * Returns the updated Matrix.
  4916. */
  4917. Matrix.prototype.addToSelf = function (other) {
  4918. for (var index = 0; index < 16; index++) {
  4919. this.m[index] += other.m[index];
  4920. }
  4921. this._markAsUpdated();
  4922. return this;
  4923. };
  4924. /**
  4925. * Sets the passed matrix with the current inverted Matrix.
  4926. * Returns the unmodified current Matrix.
  4927. */
  4928. Matrix.prototype.invertToRef = function (other) {
  4929. var l1 = this.m[0];
  4930. var l2 = this.m[1];
  4931. var l3 = this.m[2];
  4932. var l4 = this.m[3];
  4933. var l5 = this.m[4];
  4934. var l6 = this.m[5];
  4935. var l7 = this.m[6];
  4936. var l8 = this.m[7];
  4937. var l9 = this.m[8];
  4938. var l10 = this.m[9];
  4939. var l11 = this.m[10];
  4940. var l12 = this.m[11];
  4941. var l13 = this.m[12];
  4942. var l14 = this.m[13];
  4943. var l15 = this.m[14];
  4944. var l16 = this.m[15];
  4945. var l17 = (l11 * l16) - (l12 * l15);
  4946. var l18 = (l10 * l16) - (l12 * l14);
  4947. var l19 = (l10 * l15) - (l11 * l14);
  4948. var l20 = (l9 * l16) - (l12 * l13);
  4949. var l21 = (l9 * l15) - (l11 * l13);
  4950. var l22 = (l9 * l14) - (l10 * l13);
  4951. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4952. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4953. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4954. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4955. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4956. var l28 = (l7 * l16) - (l8 * l15);
  4957. var l29 = (l6 * l16) - (l8 * l14);
  4958. var l30 = (l6 * l15) - (l7 * l14);
  4959. var l31 = (l5 * l16) - (l8 * l13);
  4960. var l32 = (l5 * l15) - (l7 * l13);
  4961. var l33 = (l5 * l14) - (l6 * l13);
  4962. var l34 = (l7 * l12) - (l8 * l11);
  4963. var l35 = (l6 * l12) - (l8 * l10);
  4964. var l36 = (l6 * l11) - (l7 * l10);
  4965. var l37 = (l5 * l12) - (l8 * l9);
  4966. var l38 = (l5 * l11) - (l7 * l9);
  4967. var l39 = (l5 * l10) - (l6 * l9);
  4968. other.m[0] = l23 * l27;
  4969. other.m[4] = l24 * l27;
  4970. other.m[8] = l25 * l27;
  4971. other.m[12] = l26 * l27;
  4972. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4973. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4974. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4975. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4976. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4977. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4978. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4979. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4980. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4981. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4982. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4983. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4984. other._markAsUpdated();
  4985. return this;
  4986. };
  4987. /**
  4988. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4989. * Returns the updated Matrix.
  4990. */
  4991. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4992. this.m[12] = x;
  4993. this.m[13] = y;
  4994. this.m[14] = z;
  4995. this._markAsUpdated();
  4996. return this;
  4997. };
  4998. /**
  4999. * Inserts the translation vector in the current Matrix.
  5000. * Returns the updated Matrix.
  5001. */
  5002. Matrix.prototype.setTranslation = function (vector3) {
  5003. this.m[12] = vector3.x;
  5004. this.m[13] = vector3.y;
  5005. this.m[14] = vector3.z;
  5006. this._markAsUpdated();
  5007. return this;
  5008. };
  5009. /**
  5010. * Returns a new Vector3 as the extracted translation from the Matrix.
  5011. */
  5012. Matrix.prototype.getTranslation = function () {
  5013. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5014. };
  5015. /**
  5016. * Fill a Vector3 with the extracted translation from the Matrix.
  5017. */
  5018. Matrix.prototype.getTranslationToRef = function (result) {
  5019. result.x = this.m[12];
  5020. result.y = this.m[13];
  5021. result.z = this.m[14];
  5022. return this;
  5023. };
  5024. /**
  5025. * Remove rotation and scaling part from the Matrix.
  5026. * Returns the updated Matrix.
  5027. */
  5028. Matrix.prototype.removeRotationAndScaling = function () {
  5029. this.setRowFromFloats(0, 1, 0, 0, 0);
  5030. this.setRowFromFloats(1, 0, 1, 0, 0);
  5031. this.setRowFromFloats(2, 0, 0, 1, 0);
  5032. return this;
  5033. };
  5034. /**
  5035. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  5036. */
  5037. Matrix.prototype.multiply = function (other) {
  5038. var result = new Matrix();
  5039. this.multiplyToRef(other, result);
  5040. return result;
  5041. };
  5042. /**
  5043. * Updates the current Matrix from the passed one values.
  5044. * Returns the updated Matrix.
  5045. */
  5046. Matrix.prototype.copyFrom = function (other) {
  5047. for (var index = 0; index < 16; index++) {
  5048. this.m[index] = other.m[index];
  5049. }
  5050. this._markAsUpdated();
  5051. return this;
  5052. };
  5053. /**
  5054. * Populates the passed array from the starting index with the Matrix values.
  5055. * Returns the Matrix.
  5056. */
  5057. Matrix.prototype.copyToArray = function (array, offset) {
  5058. if (offset === void 0) { offset = 0; }
  5059. for (var index = 0; index < 16; index++) {
  5060. array[offset + index] = this.m[index];
  5061. }
  5062. return this;
  5063. };
  5064. /**
  5065. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5066. */
  5067. Matrix.prototype.multiplyToRef = function (other, result) {
  5068. this.multiplyToArray(other, result.m, 0);
  5069. result._markAsUpdated();
  5070. return this;
  5071. };
  5072. /**
  5073. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5074. */
  5075. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5076. var tm0 = this.m[0];
  5077. var tm1 = this.m[1];
  5078. var tm2 = this.m[2];
  5079. var tm3 = this.m[3];
  5080. var tm4 = this.m[4];
  5081. var tm5 = this.m[5];
  5082. var tm6 = this.m[6];
  5083. var tm7 = this.m[7];
  5084. var tm8 = this.m[8];
  5085. var tm9 = this.m[9];
  5086. var tm10 = this.m[10];
  5087. var tm11 = this.m[11];
  5088. var tm12 = this.m[12];
  5089. var tm13 = this.m[13];
  5090. var tm14 = this.m[14];
  5091. var tm15 = this.m[15];
  5092. var om0 = other.m[0];
  5093. var om1 = other.m[1];
  5094. var om2 = other.m[2];
  5095. var om3 = other.m[3];
  5096. var om4 = other.m[4];
  5097. var om5 = other.m[5];
  5098. var om6 = other.m[6];
  5099. var om7 = other.m[7];
  5100. var om8 = other.m[8];
  5101. var om9 = other.m[9];
  5102. var om10 = other.m[10];
  5103. var om11 = other.m[11];
  5104. var om12 = other.m[12];
  5105. var om13 = other.m[13];
  5106. var om14 = other.m[14];
  5107. var om15 = other.m[15];
  5108. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5109. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5110. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5111. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5112. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5113. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5114. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5115. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5116. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5117. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5118. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5119. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5120. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5121. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5122. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5123. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5124. return this;
  5125. };
  5126. /**
  5127. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5128. */
  5129. Matrix.prototype.equals = function (value) {
  5130. return value &&
  5131. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5132. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5133. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5134. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5135. };
  5136. /**
  5137. * Returns a new Matrix from the current Matrix.
  5138. */
  5139. Matrix.prototype.clone = function () {
  5140. 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]);
  5141. };
  5142. /**
  5143. * Returns the string "Matrix"
  5144. */
  5145. Matrix.prototype.getClassName = function () {
  5146. return "Matrix";
  5147. };
  5148. /**
  5149. * Returns the Matrix hash code.
  5150. */
  5151. Matrix.prototype.getHashCode = function () {
  5152. var hash = this.m[0] || 0;
  5153. for (var i = 1; i < 16; i++) {
  5154. hash = (hash * 397) ^ (this.m[i] || 0);
  5155. }
  5156. return hash;
  5157. };
  5158. /**
  5159. * Decomposes the current Matrix into :
  5160. * - a scale vector3 passed as a reference to update,
  5161. * - a rotation quaternion passed as a reference to update,
  5162. * - a translation vector3 passed as a reference to update.
  5163. * Returns the true if operation was successful.
  5164. */
  5165. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5166. translation.x = this.m[12];
  5167. translation.y = this.m[13];
  5168. translation.z = this.m[14];
  5169. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5170. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5171. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5172. if (this.determinant() <= 0) {
  5173. scale.y *= -1;
  5174. }
  5175. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5176. rotation.x = 0;
  5177. rotation.y = 0;
  5178. rotation.z = 0;
  5179. rotation.w = 1;
  5180. return false;
  5181. }
  5182. 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]);
  5183. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5184. return true;
  5185. };
  5186. /**
  5187. * Returns the index-th row of the current matrix as a new Vector4.
  5188. */
  5189. Matrix.prototype.getRow = function (index) {
  5190. if (index < 0 || index > 3) {
  5191. return null;
  5192. }
  5193. var i = index * 4;
  5194. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5195. };
  5196. /**
  5197. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5198. * Returns the updated Matrix.
  5199. */
  5200. Matrix.prototype.setRow = function (index, row) {
  5201. if (index < 0 || index > 3) {
  5202. return this;
  5203. }
  5204. var i = index * 4;
  5205. this.m[i + 0] = row.x;
  5206. this.m[i + 1] = row.y;
  5207. this.m[i + 2] = row.z;
  5208. this.m[i + 3] = row.w;
  5209. this._markAsUpdated();
  5210. return this;
  5211. };
  5212. /**
  5213. * Compute the transpose of the matrix.
  5214. * Returns a new Matrix.
  5215. */
  5216. Matrix.prototype.transpose = function () {
  5217. return Matrix.Transpose(this);
  5218. };
  5219. /**
  5220. * Compute the transpose of the matrix.
  5221. * Returns the current matrix.
  5222. */
  5223. Matrix.prototype.transposeToRef = function (result) {
  5224. Matrix.TransposeToRef(this, result);
  5225. return this;
  5226. };
  5227. /**
  5228. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5229. * Returns the updated Matrix.
  5230. */
  5231. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5232. if (index < 0 || index > 3) {
  5233. return this;
  5234. }
  5235. var i = index * 4;
  5236. this.m[i + 0] = x;
  5237. this.m[i + 1] = y;
  5238. this.m[i + 2] = z;
  5239. this.m[i + 3] = w;
  5240. this._markAsUpdated();
  5241. return this;
  5242. };
  5243. /**
  5244. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5245. * @param scale defines the scale factor
  5246. * @returns a new Matrix
  5247. */
  5248. Matrix.prototype.scale = function (scale) {
  5249. var result = new Matrix();
  5250. this.scaleToRef(scale, result);
  5251. return result;
  5252. };
  5253. /**
  5254. * Scale the current Matrix values by a factor to a given result Matrix
  5255. * @param scale defines the scale factor
  5256. * @param result defines the Matrix to store the result
  5257. * @returns the current Matrix
  5258. */
  5259. Matrix.prototype.scaleToRef = function (scale, result) {
  5260. for (var index = 0; index < 16; index++) {
  5261. result.m[index] = this.m[index] * scale;
  5262. }
  5263. result._markAsUpdated();
  5264. return this;
  5265. };
  5266. /**
  5267. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5268. * @param scale defines the scale factor
  5269. * @param result defines the Matrix to store the result
  5270. * @returns the current Matrix
  5271. */
  5272. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5273. for (var index = 0; index < 16; index++) {
  5274. result.m[index] += this.m[index] * scale;
  5275. }
  5276. result._markAsUpdated();
  5277. return this;
  5278. };
  5279. /**
  5280. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5281. * @param ref matrix to store the result
  5282. */
  5283. Matrix.prototype.toNormalMatrix = function (ref) {
  5284. this.invertToRef(ref);
  5285. ref.transpose();
  5286. var m = ref.m;
  5287. 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);
  5288. };
  5289. /**
  5290. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5291. */
  5292. Matrix.prototype.getRotationMatrix = function () {
  5293. var result = Matrix.Identity();
  5294. this.getRotationMatrixToRef(result);
  5295. return result;
  5296. };
  5297. /**
  5298. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5299. * Returns the current Matrix.
  5300. */
  5301. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5302. var m = this.m;
  5303. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5304. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5305. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5306. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5307. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5308. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5309. 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);
  5310. return this;
  5311. };
  5312. // Statics
  5313. /**
  5314. * Returns a new Matrix set from the starting index of the passed array.
  5315. */
  5316. Matrix.FromArray = function (array, offset) {
  5317. var result = new Matrix();
  5318. if (!offset) {
  5319. offset = 0;
  5320. }
  5321. Matrix.FromArrayToRef(array, offset, result);
  5322. return result;
  5323. };
  5324. /**
  5325. * Sets the passed "result" matrix from the starting index of the passed array.
  5326. */
  5327. Matrix.FromArrayToRef = function (array, offset, result) {
  5328. for (var index = 0; index < 16; index++) {
  5329. result.m[index] = array[index + offset];
  5330. }
  5331. result._markAsUpdated();
  5332. };
  5333. /**
  5334. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5335. */
  5336. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5337. for (var index = 0; index < 16; index++) {
  5338. result.m[index] = array[index + offset] * scale;
  5339. }
  5340. result._markAsUpdated();
  5341. };
  5342. /**
  5343. * Sets the passed matrix "result" with the 16 passed floats.
  5344. */
  5345. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5346. result.m[0] = initialM11;
  5347. result.m[1] = initialM12;
  5348. result.m[2] = initialM13;
  5349. result.m[3] = initialM14;
  5350. result.m[4] = initialM21;
  5351. result.m[5] = initialM22;
  5352. result.m[6] = initialM23;
  5353. result.m[7] = initialM24;
  5354. result.m[8] = initialM31;
  5355. result.m[9] = initialM32;
  5356. result.m[10] = initialM33;
  5357. result.m[11] = initialM34;
  5358. result.m[12] = initialM41;
  5359. result.m[13] = initialM42;
  5360. result.m[14] = initialM43;
  5361. result.m[15] = initialM44;
  5362. result._markAsUpdated();
  5363. };
  5364. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5365. /**
  5366. * Static identity matrix to be used as readonly matrix
  5367. * Must not be updated.
  5368. */
  5369. get: function () {
  5370. return Matrix._identityReadOnly;
  5371. },
  5372. enumerable: true,
  5373. configurable: true
  5374. });
  5375. /**
  5376. * Returns a new Matrix set from the 16 passed floats.
  5377. */
  5378. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5379. var result = new Matrix();
  5380. result.m[0] = initialM11;
  5381. result.m[1] = initialM12;
  5382. result.m[2] = initialM13;
  5383. result.m[3] = initialM14;
  5384. result.m[4] = initialM21;
  5385. result.m[5] = initialM22;
  5386. result.m[6] = initialM23;
  5387. result.m[7] = initialM24;
  5388. result.m[8] = initialM31;
  5389. result.m[9] = initialM32;
  5390. result.m[10] = initialM33;
  5391. result.m[11] = initialM34;
  5392. result.m[12] = initialM41;
  5393. result.m[13] = initialM42;
  5394. result.m[14] = initialM43;
  5395. result.m[15] = initialM44;
  5396. return result;
  5397. };
  5398. /**
  5399. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5400. */
  5401. Matrix.Compose = function (scale, rotation, translation) {
  5402. var result = Matrix.Identity();
  5403. Matrix.ComposeToRef(scale, rotation, translation, result);
  5404. return result;
  5405. };
  5406. /**
  5407. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5408. */
  5409. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5410. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5411. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5412. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5413. result.setTranslation(translation);
  5414. };
  5415. /**
  5416. * Returns a new indentity Matrix.
  5417. */
  5418. Matrix.Identity = function () {
  5419. 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);
  5420. };
  5421. /**
  5422. * Sets the passed "result" as an identity matrix.
  5423. */
  5424. Matrix.IdentityToRef = function (result) {
  5425. 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);
  5426. };
  5427. /**
  5428. * Returns a new zero Matrix.
  5429. */
  5430. Matrix.Zero = function () {
  5431. 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);
  5432. };
  5433. /**
  5434. * Returns a new rotation matrix for "angle" radians around the X axis.
  5435. */
  5436. Matrix.RotationX = function (angle) {
  5437. var result = new Matrix();
  5438. Matrix.RotationXToRef(angle, result);
  5439. return result;
  5440. };
  5441. /**
  5442. * Returns a new Matrix as the passed inverted one.
  5443. */
  5444. Matrix.Invert = function (source) {
  5445. var result = new Matrix();
  5446. source.invertToRef(result);
  5447. return result;
  5448. };
  5449. /**
  5450. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5451. */
  5452. Matrix.RotationXToRef = function (angle, result) {
  5453. var s = Math.sin(angle);
  5454. var c = Math.cos(angle);
  5455. result.m[0] = 1.0;
  5456. result.m[15] = 1.0;
  5457. result.m[5] = c;
  5458. result.m[10] = c;
  5459. result.m[9] = -s;
  5460. result.m[6] = s;
  5461. result.m[1] = 0.0;
  5462. result.m[2] = 0.0;
  5463. result.m[3] = 0.0;
  5464. result.m[4] = 0.0;
  5465. result.m[7] = 0.0;
  5466. result.m[8] = 0.0;
  5467. result.m[11] = 0.0;
  5468. result.m[12] = 0.0;
  5469. result.m[13] = 0.0;
  5470. result.m[14] = 0.0;
  5471. result._markAsUpdated();
  5472. };
  5473. /**
  5474. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5475. */
  5476. Matrix.RotationY = function (angle) {
  5477. var result = new Matrix();
  5478. Matrix.RotationYToRef(angle, result);
  5479. return result;
  5480. };
  5481. /**
  5482. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5483. */
  5484. Matrix.RotationYToRef = function (angle, result) {
  5485. var s = Math.sin(angle);
  5486. var c = Math.cos(angle);
  5487. result.m[5] = 1.0;
  5488. result.m[15] = 1.0;
  5489. result.m[0] = c;
  5490. result.m[2] = -s;
  5491. result.m[8] = s;
  5492. result.m[10] = c;
  5493. result.m[1] = 0.0;
  5494. result.m[3] = 0.0;
  5495. result.m[4] = 0.0;
  5496. result.m[6] = 0.0;
  5497. result.m[7] = 0.0;
  5498. result.m[9] = 0.0;
  5499. result.m[11] = 0.0;
  5500. result.m[12] = 0.0;
  5501. result.m[13] = 0.0;
  5502. result.m[14] = 0.0;
  5503. result._markAsUpdated();
  5504. };
  5505. /**
  5506. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5507. */
  5508. Matrix.RotationZ = function (angle) {
  5509. var result = new Matrix();
  5510. Matrix.RotationZToRef(angle, result);
  5511. return result;
  5512. };
  5513. /**
  5514. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5515. */
  5516. Matrix.RotationZToRef = function (angle, result) {
  5517. var s = Math.sin(angle);
  5518. var c = Math.cos(angle);
  5519. result.m[10] = 1.0;
  5520. result.m[15] = 1.0;
  5521. result.m[0] = c;
  5522. result.m[1] = s;
  5523. result.m[4] = -s;
  5524. result.m[5] = c;
  5525. result.m[2] = 0.0;
  5526. result.m[3] = 0.0;
  5527. result.m[6] = 0.0;
  5528. result.m[7] = 0.0;
  5529. result.m[8] = 0.0;
  5530. result.m[9] = 0.0;
  5531. result.m[11] = 0.0;
  5532. result.m[12] = 0.0;
  5533. result.m[13] = 0.0;
  5534. result.m[14] = 0.0;
  5535. result._markAsUpdated();
  5536. };
  5537. /**
  5538. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5539. */
  5540. Matrix.RotationAxis = function (axis, angle) {
  5541. var result = Matrix.Zero();
  5542. Matrix.RotationAxisToRef(axis, angle, result);
  5543. return result;
  5544. };
  5545. /**
  5546. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5547. */
  5548. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5549. var s = Math.sin(-angle);
  5550. var c = Math.cos(-angle);
  5551. var c1 = 1 - c;
  5552. axis.normalize();
  5553. result.m[0] = (axis.x * axis.x) * c1 + c;
  5554. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5555. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5556. result.m[3] = 0.0;
  5557. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5558. result.m[5] = (axis.y * axis.y) * c1 + c;
  5559. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5560. result.m[7] = 0.0;
  5561. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5562. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5563. result.m[10] = (axis.z * axis.z) * c1 + c;
  5564. result.m[11] = 0.0;
  5565. result.m[15] = 1.0;
  5566. result._markAsUpdated();
  5567. };
  5568. /**
  5569. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5570. */
  5571. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5572. var result = new Matrix();
  5573. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5574. return result;
  5575. };
  5576. /**
  5577. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5578. */
  5579. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5580. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5581. this._tempQuaternion.toRotationMatrix(result);
  5582. };
  5583. /**
  5584. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5585. */
  5586. Matrix.Scaling = function (x, y, z) {
  5587. var result = Matrix.Zero();
  5588. Matrix.ScalingToRef(x, y, z, result);
  5589. return result;
  5590. };
  5591. /**
  5592. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5593. */
  5594. Matrix.ScalingToRef = function (x, y, z, result) {
  5595. result.m[0] = x;
  5596. result.m[1] = 0.0;
  5597. result.m[2] = 0.0;
  5598. result.m[3] = 0.0;
  5599. result.m[4] = 0.0;
  5600. result.m[5] = y;
  5601. result.m[6] = 0.0;
  5602. result.m[7] = 0.0;
  5603. result.m[8] = 0.0;
  5604. result.m[9] = 0.0;
  5605. result.m[10] = z;
  5606. result.m[11] = 0.0;
  5607. result.m[12] = 0.0;
  5608. result.m[13] = 0.0;
  5609. result.m[14] = 0.0;
  5610. result.m[15] = 1.0;
  5611. result._markAsUpdated();
  5612. };
  5613. /**
  5614. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5615. */
  5616. Matrix.Translation = function (x, y, z) {
  5617. var result = Matrix.Identity();
  5618. Matrix.TranslationToRef(x, y, z, result);
  5619. return result;
  5620. };
  5621. /**
  5622. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5623. */
  5624. Matrix.TranslationToRef = function (x, y, z, result) {
  5625. 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);
  5626. };
  5627. /**
  5628. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5629. * @param startValue defines the start value
  5630. * @param endValue defines the end value
  5631. * @param gradient defines the gradient factor
  5632. * @returns the new matrix
  5633. */
  5634. Matrix.Lerp = function (startValue, endValue, gradient) {
  5635. var result = Matrix.Zero();
  5636. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5637. return result;
  5638. };
  5639. /**
  5640. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5641. * @param startValue defines the start value
  5642. * @param endValue defines the end value
  5643. * @param gradient defines the gradient factor
  5644. * @param result defines the Matrix object where to store data
  5645. */
  5646. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5647. for (var index = 0; index < 16; index++) {
  5648. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5649. }
  5650. result._markAsUpdated();
  5651. };
  5652. /**
  5653. * Returns a new Matrix whose values are computed by :
  5654. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5655. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5656. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5657. */
  5658. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5659. var startScale = new Vector3(0, 0, 0);
  5660. var startRotation = new Quaternion();
  5661. var startTranslation = new Vector3(0, 0, 0);
  5662. startValue.decompose(startScale, startRotation, startTranslation);
  5663. var endScale = new Vector3(0, 0, 0);
  5664. var endRotation = new Quaternion();
  5665. var endTranslation = new Vector3(0, 0, 0);
  5666. endValue.decompose(endScale, endRotation, endTranslation);
  5667. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5668. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5669. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5670. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5671. };
  5672. /**
  5673. * 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".
  5674. * This methods works for a Left-Handed system.
  5675. */
  5676. Matrix.LookAtLH = function (eye, target, up) {
  5677. var result = Matrix.Zero();
  5678. Matrix.LookAtLHToRef(eye, target, up, result);
  5679. return result;
  5680. };
  5681. /**
  5682. * 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".
  5683. * This methods works for a Left-Handed system.
  5684. */
  5685. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5686. // Z axis
  5687. target.subtractToRef(eye, this._zAxis);
  5688. this._zAxis.normalize();
  5689. // X axis
  5690. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5691. if (this._xAxis.lengthSquared() === 0) {
  5692. this._xAxis.x = 1.0;
  5693. }
  5694. else {
  5695. this._xAxis.normalize();
  5696. }
  5697. // Y axis
  5698. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5699. this._yAxis.normalize();
  5700. // Eye angles
  5701. var ex = -Vector3.Dot(this._xAxis, eye);
  5702. var ey = -Vector3.Dot(this._yAxis, eye);
  5703. var ez = -Vector3.Dot(this._zAxis, eye);
  5704. 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);
  5705. };
  5706. /**
  5707. * 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".
  5708. * This methods works for a Right-Handed system.
  5709. */
  5710. Matrix.LookAtRH = function (eye, target, up) {
  5711. var result = Matrix.Zero();
  5712. Matrix.LookAtRHToRef(eye, target, up, result);
  5713. return result;
  5714. };
  5715. /**
  5716. * 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".
  5717. * This methods works for a Left-Handed system.
  5718. */
  5719. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5720. // Z axis
  5721. eye.subtractToRef(target, this._zAxis);
  5722. this._zAxis.normalize();
  5723. // X axis
  5724. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5725. if (this._xAxis.lengthSquared() === 0) {
  5726. this._xAxis.x = 1.0;
  5727. }
  5728. else {
  5729. this._xAxis.normalize();
  5730. }
  5731. // Y axis
  5732. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5733. this._yAxis.normalize();
  5734. // Eye angles
  5735. var ex = -Vector3.Dot(this._xAxis, eye);
  5736. var ey = -Vector3.Dot(this._yAxis, eye);
  5737. var ez = -Vector3.Dot(this._zAxis, eye);
  5738. 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);
  5739. };
  5740. /**
  5741. * 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.
  5742. */
  5743. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5744. var matrix = Matrix.Zero();
  5745. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5746. return matrix;
  5747. };
  5748. /**
  5749. * 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.
  5750. */
  5751. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5752. var n = znear;
  5753. var f = zfar;
  5754. var a = 2.0 / width;
  5755. var b = 2.0 / height;
  5756. var c = 2.0 / (f - n);
  5757. var d = -(f + n) / (f - n);
  5758. 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);
  5759. };
  5760. /**
  5761. * 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.
  5762. */
  5763. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5764. var matrix = Matrix.Zero();
  5765. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5766. return matrix;
  5767. };
  5768. /**
  5769. * 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.
  5770. */
  5771. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5772. var n = znear;
  5773. var f = zfar;
  5774. var a = 2.0 / (right - left);
  5775. var b = 2.0 / (top - bottom);
  5776. var c = 2.0 / (f - n);
  5777. var d = -(f + n) / (f - n);
  5778. var i0 = (left + right) / (left - right);
  5779. var i1 = (top + bottom) / (bottom - top);
  5780. 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);
  5781. };
  5782. /**
  5783. * 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.
  5784. */
  5785. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5786. var matrix = Matrix.Zero();
  5787. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5788. return matrix;
  5789. };
  5790. /**
  5791. * 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.
  5792. */
  5793. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5794. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5795. result.m[10] *= -1.0;
  5796. };
  5797. /**
  5798. * 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.
  5799. */
  5800. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5801. var matrix = Matrix.Zero();
  5802. var n = znear;
  5803. var f = zfar;
  5804. var a = 2.0 * n / width;
  5805. var b = 2.0 * n / height;
  5806. var c = (f + n) / (f - n);
  5807. var d = -2.0 * f * n / (f - n);
  5808. 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);
  5809. return matrix;
  5810. };
  5811. /**
  5812. * 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.
  5813. */
  5814. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5815. var matrix = Matrix.Zero();
  5816. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5817. return matrix;
  5818. };
  5819. /**
  5820. * 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.
  5821. */
  5822. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5823. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5824. var n = znear;
  5825. var f = zfar;
  5826. var t = 1.0 / (Math.tan(fov * 0.5));
  5827. var a = isVerticalFovFixed ? (t / aspect) : t;
  5828. var b = isVerticalFovFixed ? t : (t * aspect);
  5829. var c = (f + n) / (f - n);
  5830. var d = -2.0 * f * n / (f - n);
  5831. 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);
  5832. };
  5833. /**
  5834. * 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.
  5835. */
  5836. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5837. var matrix = Matrix.Zero();
  5838. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5839. return matrix;
  5840. };
  5841. /**
  5842. * 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.
  5843. */
  5844. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5845. //alternatively this could be expressed as:
  5846. // m = PerspectiveFovLHToRef
  5847. // m[10] *= -1.0;
  5848. // m[11] *= -1.0;
  5849. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5850. var n = znear;
  5851. var f = zfar;
  5852. var t = 1.0 / (Math.tan(fov * 0.5));
  5853. var a = isVerticalFovFixed ? (t / aspect) : t;
  5854. var b = isVerticalFovFixed ? t : (t * aspect);
  5855. var c = -(f + n) / (f - n);
  5856. var d = -2 * f * n / (f - n);
  5857. 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);
  5858. };
  5859. /**
  5860. * 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.
  5861. */
  5862. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5863. if (rightHanded === void 0) { rightHanded = false; }
  5864. var rightHandedFactor = rightHanded ? -1 : 1;
  5865. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5866. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5867. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5868. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5869. var xScale = 2.0 / (leftTan + rightTan);
  5870. var yScale = 2.0 / (upTan + downTan);
  5871. result.m[0] = xScale;
  5872. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5873. result.m[5] = yScale;
  5874. result.m[6] = result.m[7] = 0.0;
  5875. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5876. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5877. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5878. result.m[10] = -zfar / (znear - zfar);
  5879. result.m[11] = 1.0 * rightHandedFactor;
  5880. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5881. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5882. // result.m[14] = (znear * zfar) / (znear - zfar);
  5883. result._markAsUpdated();
  5884. };
  5885. /**
  5886. * Returns the final transformation matrix : world * view * projection * viewport
  5887. */
  5888. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5889. var cw = viewport.width;
  5890. var ch = viewport.height;
  5891. var cx = viewport.x;
  5892. var cy = viewport.y;
  5893. 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);
  5894. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5895. };
  5896. /**
  5897. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5898. */
  5899. Matrix.GetAsMatrix2x2 = function (matrix) {
  5900. return new Float32Array([
  5901. matrix.m[0], matrix.m[1],
  5902. matrix.m[4], matrix.m[5]
  5903. ]);
  5904. };
  5905. /**
  5906. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5907. */
  5908. Matrix.GetAsMatrix3x3 = function (matrix) {
  5909. return new Float32Array([
  5910. matrix.m[0], matrix.m[1], matrix.m[2],
  5911. matrix.m[4], matrix.m[5], matrix.m[6],
  5912. matrix.m[8], matrix.m[9], matrix.m[10]
  5913. ]);
  5914. };
  5915. /**
  5916. * Compute the transpose of the passed Matrix.
  5917. * Returns a new Matrix.
  5918. */
  5919. Matrix.Transpose = function (matrix) {
  5920. var result = new Matrix();
  5921. Matrix.TransposeToRef(matrix, result);
  5922. return result;
  5923. };
  5924. /**
  5925. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5926. */
  5927. Matrix.TransposeToRef = function (matrix, result) {
  5928. result.m[0] = matrix.m[0];
  5929. result.m[1] = matrix.m[4];
  5930. result.m[2] = matrix.m[8];
  5931. result.m[3] = matrix.m[12];
  5932. result.m[4] = matrix.m[1];
  5933. result.m[5] = matrix.m[5];
  5934. result.m[6] = matrix.m[9];
  5935. result.m[7] = matrix.m[13];
  5936. result.m[8] = matrix.m[2];
  5937. result.m[9] = matrix.m[6];
  5938. result.m[10] = matrix.m[10];
  5939. result.m[11] = matrix.m[14];
  5940. result.m[12] = matrix.m[3];
  5941. result.m[13] = matrix.m[7];
  5942. result.m[14] = matrix.m[11];
  5943. result.m[15] = matrix.m[15];
  5944. };
  5945. /**
  5946. * Returns a new Matrix as the reflection matrix across the passed plane.
  5947. */
  5948. Matrix.Reflection = function (plane) {
  5949. var matrix = new Matrix();
  5950. Matrix.ReflectionToRef(plane, matrix);
  5951. return matrix;
  5952. };
  5953. /**
  5954. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5955. */
  5956. Matrix.ReflectionToRef = function (plane, result) {
  5957. plane.normalize();
  5958. var x = plane.normal.x;
  5959. var y = plane.normal.y;
  5960. var z = plane.normal.z;
  5961. var temp = -2 * x;
  5962. var temp2 = -2 * y;
  5963. var temp3 = -2 * z;
  5964. result.m[0] = (temp * x) + 1;
  5965. result.m[1] = temp2 * x;
  5966. result.m[2] = temp3 * x;
  5967. result.m[3] = 0.0;
  5968. result.m[4] = temp * y;
  5969. result.m[5] = (temp2 * y) + 1;
  5970. result.m[6] = temp3 * y;
  5971. result.m[7] = 0.0;
  5972. result.m[8] = temp * z;
  5973. result.m[9] = temp2 * z;
  5974. result.m[10] = (temp3 * z) + 1;
  5975. result.m[11] = 0.0;
  5976. result.m[12] = temp * plane.d;
  5977. result.m[13] = temp2 * plane.d;
  5978. result.m[14] = temp3 * plane.d;
  5979. result.m[15] = 1.0;
  5980. result._markAsUpdated();
  5981. };
  5982. /**
  5983. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5984. */
  5985. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5986. result.m[0] = xaxis.x;
  5987. result.m[1] = xaxis.y;
  5988. result.m[2] = xaxis.z;
  5989. result.m[3] = 0.0;
  5990. result.m[4] = yaxis.x;
  5991. result.m[5] = yaxis.y;
  5992. result.m[6] = yaxis.z;
  5993. result.m[7] = 0.0;
  5994. result.m[8] = zaxis.x;
  5995. result.m[9] = zaxis.y;
  5996. result.m[10] = zaxis.z;
  5997. result.m[11] = 0.0;
  5998. result.m[12] = 0.0;
  5999. result.m[13] = 0.0;
  6000. result.m[14] = 0.0;
  6001. result.m[15] = 1.0;
  6002. result._markAsUpdated();
  6003. };
  6004. /**
  6005. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  6006. */
  6007. Matrix.FromQuaternionToRef = function (quat, result) {
  6008. var xx = quat.x * quat.x;
  6009. var yy = quat.y * quat.y;
  6010. var zz = quat.z * quat.z;
  6011. var xy = quat.x * quat.y;
  6012. var zw = quat.z * quat.w;
  6013. var zx = quat.z * quat.x;
  6014. var yw = quat.y * quat.w;
  6015. var yz = quat.y * quat.z;
  6016. var xw = quat.x * quat.w;
  6017. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6018. result.m[1] = 2.0 * (xy + zw);
  6019. result.m[2] = 2.0 * (zx - yw);
  6020. result.m[3] = 0.0;
  6021. result.m[4] = 2.0 * (xy - zw);
  6022. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6023. result.m[6] = 2.0 * (yz + xw);
  6024. result.m[7] = 0.0;
  6025. result.m[8] = 2.0 * (zx + yw);
  6026. result.m[9] = 2.0 * (yz - xw);
  6027. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6028. result.m[11] = 0.0;
  6029. result.m[12] = 0.0;
  6030. result.m[13] = 0.0;
  6031. result.m[14] = 0.0;
  6032. result.m[15] = 1.0;
  6033. result._markAsUpdated();
  6034. };
  6035. Matrix._tempQuaternion = new Quaternion();
  6036. Matrix._xAxis = Vector3.Zero();
  6037. Matrix._yAxis = Vector3.Zero();
  6038. Matrix._zAxis = Vector3.Zero();
  6039. Matrix._updateFlagSeed = 0;
  6040. Matrix._identityReadOnly = Matrix.Identity();
  6041. return Matrix;
  6042. }());
  6043. BABYLON.Matrix = Matrix;
  6044. var Plane = /** @class */ (function () {
  6045. /**
  6046. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6047. */
  6048. function Plane(a, b, c, d) {
  6049. this.normal = new Vector3(a, b, c);
  6050. this.d = d;
  6051. }
  6052. /**
  6053. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6054. */
  6055. Plane.prototype.asArray = function () {
  6056. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6057. };
  6058. // Methods
  6059. /**
  6060. * Returns a new plane copied from the current Plane.
  6061. */
  6062. Plane.prototype.clone = function () {
  6063. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6064. };
  6065. /**
  6066. * Returns the string "Plane".
  6067. */
  6068. Plane.prototype.getClassName = function () {
  6069. return "Plane";
  6070. };
  6071. /**
  6072. * Returns the Plane hash code.
  6073. */
  6074. Plane.prototype.getHashCode = function () {
  6075. var hash = this.normal.getHashCode();
  6076. hash = (hash * 397) ^ (this.d || 0);
  6077. return hash;
  6078. };
  6079. /**
  6080. * Normalize the current Plane in place.
  6081. * Returns the updated Plane.
  6082. */
  6083. Plane.prototype.normalize = function () {
  6084. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6085. var magnitude = 0.0;
  6086. if (norm !== 0) {
  6087. magnitude = 1.0 / norm;
  6088. }
  6089. this.normal.x *= magnitude;
  6090. this.normal.y *= magnitude;
  6091. this.normal.z *= magnitude;
  6092. this.d *= magnitude;
  6093. return this;
  6094. };
  6095. /**
  6096. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6097. */
  6098. Plane.prototype.transform = function (transformation) {
  6099. var transposedMatrix = Matrix.Transpose(transformation);
  6100. var x = this.normal.x;
  6101. var y = this.normal.y;
  6102. var z = this.normal.z;
  6103. var d = this.d;
  6104. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6105. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6106. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6107. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6108. return new Plane(normalX, normalY, normalZ, finalD);
  6109. };
  6110. /**
  6111. * Returns the dot product (float) of the point coordinates and the plane normal.
  6112. */
  6113. Plane.prototype.dotCoordinate = function (point) {
  6114. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6115. };
  6116. /**
  6117. * Updates the current Plane from the plane defined by the three passed points.
  6118. * Returns the updated Plane.
  6119. */
  6120. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6121. var x1 = point2.x - point1.x;
  6122. var y1 = point2.y - point1.y;
  6123. var z1 = point2.z - point1.z;
  6124. var x2 = point3.x - point1.x;
  6125. var y2 = point3.y - point1.y;
  6126. var z2 = point3.z - point1.z;
  6127. var yz = (y1 * z2) - (z1 * y2);
  6128. var xz = (z1 * x2) - (x1 * z2);
  6129. var xy = (x1 * y2) - (y1 * x2);
  6130. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6131. var invPyth;
  6132. if (pyth !== 0) {
  6133. invPyth = 1.0 / pyth;
  6134. }
  6135. else {
  6136. invPyth = 0.0;
  6137. }
  6138. this.normal.x = yz * invPyth;
  6139. this.normal.y = xz * invPyth;
  6140. this.normal.z = xy * invPyth;
  6141. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6142. return this;
  6143. };
  6144. /**
  6145. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6146. */
  6147. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6148. var dot = Vector3.Dot(this.normal, direction);
  6149. return (dot <= epsilon);
  6150. };
  6151. /**
  6152. * Returns the signed distance (float) from the passed point to the Plane.
  6153. */
  6154. Plane.prototype.signedDistanceTo = function (point) {
  6155. return Vector3.Dot(point, this.normal) + this.d;
  6156. };
  6157. // Statics
  6158. /**
  6159. * Returns a new Plane from the passed array.
  6160. */
  6161. Plane.FromArray = function (array) {
  6162. return new Plane(array[0], array[1], array[2], array[3]);
  6163. };
  6164. /**
  6165. * Returns a new Plane defined by the three passed points.
  6166. */
  6167. Plane.FromPoints = function (point1, point2, point3) {
  6168. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6169. result.copyFromPoints(point1, point2, point3);
  6170. return result;
  6171. };
  6172. /**
  6173. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6174. * Note : the vector "normal" is updated because normalized.
  6175. */
  6176. Plane.FromPositionAndNormal = function (origin, normal) {
  6177. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6178. normal.normalize();
  6179. result.normal = normal;
  6180. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6181. return result;
  6182. };
  6183. /**
  6184. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6185. */
  6186. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6187. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6188. return Vector3.Dot(point, normal) + d;
  6189. };
  6190. return Plane;
  6191. }());
  6192. BABYLON.Plane = Plane;
  6193. var Viewport = /** @class */ (function () {
  6194. /**
  6195. * Creates a Viewport object located at (x, y) and sized (width, height).
  6196. */
  6197. function Viewport(x, y, width, height) {
  6198. this.x = x;
  6199. this.y = y;
  6200. this.width = width;
  6201. this.height = height;
  6202. }
  6203. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6204. if (renderWidthOrEngine.getRenderWidth) {
  6205. var engine = renderWidthOrEngine;
  6206. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6207. }
  6208. var renderWidth = renderWidthOrEngine;
  6209. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6210. };
  6211. /**
  6212. * Returns a new Viewport copied from the current one.
  6213. */
  6214. Viewport.prototype.clone = function () {
  6215. return new Viewport(this.x, this.y, this.width, this.height);
  6216. };
  6217. return Viewport;
  6218. }());
  6219. BABYLON.Viewport = Viewport;
  6220. var Frustum = /** @class */ (function () {
  6221. function Frustum() {
  6222. }
  6223. /**
  6224. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6225. */
  6226. Frustum.GetPlanes = function (transform) {
  6227. var frustumPlanes = [];
  6228. for (var index = 0; index < 6; index++) {
  6229. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6230. }
  6231. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6232. return frustumPlanes;
  6233. };
  6234. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6235. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6236. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6237. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6238. frustumPlane.d = transform.m[15] + transform.m[14];
  6239. frustumPlane.normalize();
  6240. };
  6241. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6242. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6243. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6244. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6245. frustumPlane.d = transform.m[15] - transform.m[14];
  6246. frustumPlane.normalize();
  6247. };
  6248. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6249. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6250. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6251. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6252. frustumPlane.d = transform.m[15] + transform.m[12];
  6253. frustumPlane.normalize();
  6254. };
  6255. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6256. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6257. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6258. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6259. frustumPlane.d = transform.m[15] - transform.m[12];
  6260. frustumPlane.normalize();
  6261. };
  6262. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6263. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6264. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6265. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6266. frustumPlane.d = transform.m[15] - transform.m[13];
  6267. frustumPlane.normalize();
  6268. };
  6269. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6270. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6271. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6272. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6273. frustumPlane.d = transform.m[15] + transform.m[13];
  6274. frustumPlane.normalize();
  6275. };
  6276. /**
  6277. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6278. */
  6279. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6280. // Near
  6281. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6282. // Far
  6283. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6284. // Left
  6285. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6286. // Right
  6287. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6288. // Top
  6289. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6290. // Bottom
  6291. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6292. };
  6293. return Frustum;
  6294. }());
  6295. BABYLON.Frustum = Frustum;
  6296. var Space;
  6297. (function (Space) {
  6298. Space[Space["LOCAL"] = 0] = "LOCAL";
  6299. Space[Space["WORLD"] = 1] = "WORLD";
  6300. Space[Space["BONE"] = 2] = "BONE";
  6301. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6302. var Axis = /** @class */ (function () {
  6303. function Axis() {
  6304. }
  6305. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6306. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6307. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6308. return Axis;
  6309. }());
  6310. BABYLON.Axis = Axis;
  6311. ;
  6312. var BezierCurve = /** @class */ (function () {
  6313. function BezierCurve() {
  6314. }
  6315. /**
  6316. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6317. */
  6318. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6319. // Extract X (which is equal to time here)
  6320. var f0 = 1 - 3 * x2 + 3 * x1;
  6321. var f1 = 3 * x2 - 6 * x1;
  6322. var f2 = 3 * x1;
  6323. var refinedT = t;
  6324. for (var i = 0; i < 5; i++) {
  6325. var refinedT2 = refinedT * refinedT;
  6326. var refinedT3 = refinedT2 * refinedT;
  6327. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6328. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6329. refinedT -= (x - t) * slope;
  6330. refinedT = Math.min(1, Math.max(0, refinedT));
  6331. }
  6332. // Resolve cubic bezier for the given x
  6333. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6334. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6335. Math.pow(refinedT, 3);
  6336. };
  6337. return BezierCurve;
  6338. }());
  6339. BABYLON.BezierCurve = BezierCurve;
  6340. var Orientation;
  6341. (function (Orientation) {
  6342. Orientation[Orientation["CW"] = 0] = "CW";
  6343. Orientation[Orientation["CCW"] = 1] = "CCW";
  6344. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6345. var Angle = /** @class */ (function () {
  6346. /**
  6347. * Creates an Angle object of "radians" radians (float).
  6348. */
  6349. function Angle(radians) {
  6350. var _this = this;
  6351. /**
  6352. * Returns the Angle value in degrees (float).
  6353. */
  6354. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6355. /**
  6356. * Returns the Angle value in radians (float).
  6357. */
  6358. this.radians = function () { return _this._radians; };
  6359. this._radians = radians;
  6360. if (this._radians < 0.0)
  6361. this._radians += (2.0 * Math.PI);
  6362. }
  6363. /**
  6364. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6365. */
  6366. Angle.BetweenTwoPoints = function (a, b) {
  6367. var delta = b.subtract(a);
  6368. var theta = Math.atan2(delta.y, delta.x);
  6369. return new Angle(theta);
  6370. };
  6371. /**
  6372. * Returns a new Angle object from the passed float in radians.
  6373. */
  6374. Angle.FromRadians = function (radians) {
  6375. return new Angle(radians);
  6376. };
  6377. /**
  6378. * Returns a new Angle object from the passed float in degrees.
  6379. */
  6380. Angle.FromDegrees = function (degrees) {
  6381. return new Angle(degrees * Math.PI / 180.0);
  6382. };
  6383. return Angle;
  6384. }());
  6385. BABYLON.Angle = Angle;
  6386. var Arc2 = /** @class */ (function () {
  6387. /**
  6388. * Creates an Arc object from the three passed points : start, middle and end.
  6389. */
  6390. function Arc2(startPoint, midPoint, endPoint) {
  6391. this.startPoint = startPoint;
  6392. this.midPoint = midPoint;
  6393. this.endPoint = endPoint;
  6394. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6395. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6396. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6397. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6398. 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);
  6399. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6400. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6401. var a1 = this.startAngle.degrees();
  6402. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6403. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6404. // angles correction
  6405. if (a2 - a1 > +180.0)
  6406. a2 -= 360.0;
  6407. if (a2 - a1 < -180.0)
  6408. a2 += 360.0;
  6409. if (a3 - a2 > +180.0)
  6410. a3 -= 360.0;
  6411. if (a3 - a2 < -180.0)
  6412. a3 += 360.0;
  6413. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6414. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6415. }
  6416. return Arc2;
  6417. }());
  6418. BABYLON.Arc2 = Arc2;
  6419. var Path2 = /** @class */ (function () {
  6420. /**
  6421. * Creates a Path2 object from the starting 2D coordinates x and y.
  6422. */
  6423. function Path2(x, y) {
  6424. this._points = new Array();
  6425. this._length = 0.0;
  6426. this.closed = false;
  6427. this._points.push(new Vector2(x, y));
  6428. }
  6429. /**
  6430. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6431. * Returns the updated Path2.
  6432. */
  6433. Path2.prototype.addLineTo = function (x, y) {
  6434. if (this.closed) {
  6435. return this;
  6436. }
  6437. var newPoint = new Vector2(x, y);
  6438. var previousPoint = this._points[this._points.length - 1];
  6439. this._points.push(newPoint);
  6440. this._length += newPoint.subtract(previousPoint).length();
  6441. return this;
  6442. };
  6443. /**
  6444. * 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.
  6445. * Returns the updated Path2.
  6446. */
  6447. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6448. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6449. if (this.closed) {
  6450. return this;
  6451. }
  6452. var startPoint = this._points[this._points.length - 1];
  6453. var midPoint = new Vector2(midX, midY);
  6454. var endPoint = new Vector2(endX, endY);
  6455. var arc = new Arc2(startPoint, midPoint, endPoint);
  6456. var increment = arc.angle.radians() / numberOfSegments;
  6457. if (arc.orientation === Orientation.CW)
  6458. increment *= -1;
  6459. var currentAngle = arc.startAngle.radians() + increment;
  6460. for (var i = 0; i < numberOfSegments; i++) {
  6461. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6462. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6463. this.addLineTo(x, y);
  6464. currentAngle += increment;
  6465. }
  6466. return this;
  6467. };
  6468. /**
  6469. * Closes the Path2.
  6470. * Returns the Path2.
  6471. */
  6472. Path2.prototype.close = function () {
  6473. this.closed = true;
  6474. return this;
  6475. };
  6476. /**
  6477. * Returns the Path2 total length (float).
  6478. */
  6479. Path2.prototype.length = function () {
  6480. var result = this._length;
  6481. if (!this.closed) {
  6482. var lastPoint = this._points[this._points.length - 1];
  6483. var firstPoint = this._points[0];
  6484. result += (firstPoint.subtract(lastPoint).length());
  6485. }
  6486. return result;
  6487. };
  6488. /**
  6489. * Returns the Path2 internal array of points.
  6490. */
  6491. Path2.prototype.getPoints = function () {
  6492. return this._points;
  6493. };
  6494. /**
  6495. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6496. */
  6497. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6498. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6499. return Vector2.Zero();
  6500. }
  6501. var lengthPosition = normalizedLengthPosition * this.length();
  6502. var previousOffset = 0;
  6503. for (var i = 0; i < this._points.length; i++) {
  6504. var j = (i + 1) % this._points.length;
  6505. var a = this._points[i];
  6506. var b = this._points[j];
  6507. var bToA = b.subtract(a);
  6508. var nextOffset = (bToA.length() + previousOffset);
  6509. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6510. var dir = bToA.normalize();
  6511. var localOffset = lengthPosition - previousOffset;
  6512. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6513. }
  6514. previousOffset = nextOffset;
  6515. }
  6516. return Vector2.Zero();
  6517. };
  6518. /**
  6519. * Returns a new Path2 starting at the coordinates (x, y).
  6520. */
  6521. Path2.StartingAt = function (x, y) {
  6522. return new Path2(x, y);
  6523. };
  6524. return Path2;
  6525. }());
  6526. BABYLON.Path2 = Path2;
  6527. var Path3D = /** @class */ (function () {
  6528. /**
  6529. * new Path3D(path, normal, raw)
  6530. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6531. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6532. * path : an array of Vector3, the curve axis of the Path3D
  6533. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6534. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6535. */
  6536. function Path3D(path, firstNormal, raw) {
  6537. if (firstNormal === void 0) { firstNormal = null; }
  6538. this.path = path;
  6539. this._curve = new Array();
  6540. this._distances = new Array();
  6541. this._tangents = new Array();
  6542. this._normals = new Array();
  6543. this._binormals = new Array();
  6544. for (var p = 0; p < path.length; p++) {
  6545. this._curve[p] = path[p].clone(); // hard copy
  6546. }
  6547. this._raw = raw || false;
  6548. this._compute(firstNormal);
  6549. }
  6550. /**
  6551. * Returns the Path3D array of successive Vector3 designing its curve.
  6552. */
  6553. Path3D.prototype.getCurve = function () {
  6554. return this._curve;
  6555. };
  6556. /**
  6557. * Returns an array populated with tangent vectors on each Path3D curve point.
  6558. */
  6559. Path3D.prototype.getTangents = function () {
  6560. return this._tangents;
  6561. };
  6562. /**
  6563. * Returns an array populated with normal vectors on each Path3D curve point.
  6564. */
  6565. Path3D.prototype.getNormals = function () {
  6566. return this._normals;
  6567. };
  6568. /**
  6569. * Returns an array populated with binormal vectors on each Path3D curve point.
  6570. */
  6571. Path3D.prototype.getBinormals = function () {
  6572. return this._binormals;
  6573. };
  6574. /**
  6575. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6576. */
  6577. Path3D.prototype.getDistances = function () {
  6578. return this._distances;
  6579. };
  6580. /**
  6581. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6582. * Returns the same object updated.
  6583. */
  6584. Path3D.prototype.update = function (path, firstNormal) {
  6585. if (firstNormal === void 0) { firstNormal = null; }
  6586. for (var p = 0; p < path.length; p++) {
  6587. this._curve[p].x = path[p].x;
  6588. this._curve[p].y = path[p].y;
  6589. this._curve[p].z = path[p].z;
  6590. }
  6591. this._compute(firstNormal);
  6592. return this;
  6593. };
  6594. // private function compute() : computes tangents, normals and binormals
  6595. Path3D.prototype._compute = function (firstNormal) {
  6596. var l = this._curve.length;
  6597. // first and last tangents
  6598. this._tangents[0] = this._getFirstNonNullVector(0);
  6599. if (!this._raw) {
  6600. this._tangents[0].normalize();
  6601. }
  6602. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6603. if (!this._raw) {
  6604. this._tangents[l - 1].normalize();
  6605. }
  6606. // normals and binormals at first point : arbitrary vector with _normalVector()
  6607. var tg0 = this._tangents[0];
  6608. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6609. this._normals[0] = pp0;
  6610. if (!this._raw) {
  6611. this._normals[0].normalize();
  6612. }
  6613. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6614. if (!this._raw) {
  6615. this._binormals[0].normalize();
  6616. }
  6617. this._distances[0] = 0.0;
  6618. // normals and binormals : next points
  6619. var prev; // previous vector (segment)
  6620. var cur; // current vector (segment)
  6621. var curTang; // current tangent
  6622. // previous normal
  6623. var prevBinor; // previous binormal
  6624. for (var i = 1; i < l; i++) {
  6625. // tangents
  6626. prev = this._getLastNonNullVector(i);
  6627. if (i < l - 1) {
  6628. cur = this._getFirstNonNullVector(i);
  6629. this._tangents[i] = prev.add(cur);
  6630. this._tangents[i].normalize();
  6631. }
  6632. this._distances[i] = this._distances[i - 1] + prev.length();
  6633. // normals and binormals
  6634. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6635. curTang = this._tangents[i];
  6636. prevBinor = this._binormals[i - 1];
  6637. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6638. if (!this._raw) {
  6639. this._normals[i].normalize();
  6640. }
  6641. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6642. if (!this._raw) {
  6643. this._binormals[i].normalize();
  6644. }
  6645. }
  6646. };
  6647. // private function getFirstNonNullVector(index)
  6648. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6649. Path3D.prototype._getFirstNonNullVector = function (index) {
  6650. var i = 1;
  6651. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6652. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6653. i++;
  6654. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6655. }
  6656. return nNVector;
  6657. };
  6658. // private function getLastNonNullVector(index)
  6659. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6660. Path3D.prototype._getLastNonNullVector = function (index) {
  6661. var i = 1;
  6662. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6663. while (nLVector.length() === 0 && index > i + 1) {
  6664. i++;
  6665. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6666. }
  6667. return nLVector;
  6668. };
  6669. // private function normalVector(v0, vt, va) :
  6670. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6671. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6672. Path3D.prototype._normalVector = function (v0, vt, va) {
  6673. var normal0;
  6674. var tgl = vt.length();
  6675. if (tgl === 0.0) {
  6676. tgl = 1.0;
  6677. }
  6678. if (va === undefined || va === null) {
  6679. var point;
  6680. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6681. point = new Vector3(0.0, -1.0, 0.0);
  6682. }
  6683. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6684. point = new Vector3(1.0, 0.0, 0.0);
  6685. }
  6686. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6687. point = new Vector3(0.0, 0.0, 1.0);
  6688. }
  6689. else {
  6690. point = Vector3.Zero();
  6691. }
  6692. normal0 = Vector3.Cross(vt, point);
  6693. }
  6694. else {
  6695. normal0 = Vector3.Cross(vt, va);
  6696. Vector3.CrossToRef(normal0, vt, normal0);
  6697. }
  6698. normal0.normalize();
  6699. return normal0;
  6700. };
  6701. return Path3D;
  6702. }());
  6703. BABYLON.Path3D = Path3D;
  6704. var Curve3 = /** @class */ (function () {
  6705. /**
  6706. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6707. * A Curve3 is designed from a series of successive Vector3.
  6708. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6709. */
  6710. function Curve3(points) {
  6711. this._length = 0.0;
  6712. this._points = points;
  6713. this._length = this._computeLength(points);
  6714. }
  6715. /**
  6716. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6717. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6718. * @param v1 (Vector3) the control point
  6719. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6720. * @param nbPoints (integer) the wanted number of points in the curve
  6721. */
  6722. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6723. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6724. var bez = new Array();
  6725. var equation = function (t, val0, val1, val2) {
  6726. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6727. return res;
  6728. };
  6729. for (var i = 0; i <= nbPoints; i++) {
  6730. 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)));
  6731. }
  6732. return new Curve3(bez);
  6733. };
  6734. /**
  6735. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6736. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6737. * @param v1 (Vector3) the first control point
  6738. * @param v2 (Vector3) the second control point
  6739. * @param v3 (Vector3) the end point of the Cubic Bezier
  6740. * @param nbPoints (integer) the wanted number of points in the curve
  6741. */
  6742. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6743. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6744. var bez = new Array();
  6745. var equation = function (t, val0, val1, val2, val3) {
  6746. 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;
  6747. return res;
  6748. };
  6749. for (var i = 0; i <= nbPoints; i++) {
  6750. 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)));
  6751. }
  6752. return new Curve3(bez);
  6753. };
  6754. /**
  6755. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6756. * @param p1 (Vector3) the origin point of the Hermite Spline
  6757. * @param t1 (Vector3) the tangent vector at the origin point
  6758. * @param p2 (Vector3) the end point of the Hermite Spline
  6759. * @param t2 (Vector3) the tangent vector at the end point
  6760. * @param nbPoints (integer) the wanted number of points in the curve
  6761. */
  6762. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6763. var hermite = new Array();
  6764. var step = 1.0 / nbPoints;
  6765. for (var i = 0; i <= nbPoints; i++) {
  6766. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6767. }
  6768. return new Curve3(hermite);
  6769. };
  6770. /**
  6771. * Returns a Curve3 object along a CatmullRom Spline curve :
  6772. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6773. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6774. */
  6775. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6776. var totalPoints = new Array();
  6777. totalPoints.push(points[0].clone());
  6778. Array.prototype.push.apply(totalPoints, points);
  6779. totalPoints.push(points[points.length - 1].clone());
  6780. var catmullRom = new Array();
  6781. var step = 1.0 / nbPoints;
  6782. var amount = 0.0;
  6783. for (var i = 0; i < totalPoints.length - 3; i++) {
  6784. amount = 0;
  6785. for (var c = 0; c < nbPoints; c++) {
  6786. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6787. amount += step;
  6788. }
  6789. }
  6790. i--;
  6791. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6792. return new Curve3(catmullRom);
  6793. };
  6794. /**
  6795. * Returns the Curve3 stored array of successive Vector3
  6796. */
  6797. Curve3.prototype.getPoints = function () {
  6798. return this._points;
  6799. };
  6800. /**
  6801. * Returns the computed length (float) of the curve.
  6802. */
  6803. Curve3.prototype.length = function () {
  6804. return this._length;
  6805. };
  6806. /**
  6807. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6808. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6809. * curveA and curveB keep unchanged.
  6810. */
  6811. Curve3.prototype.continue = function (curve) {
  6812. var lastPoint = this._points[this._points.length - 1];
  6813. var continuedPoints = this._points.slice();
  6814. var curvePoints = curve.getPoints();
  6815. for (var i = 1; i < curvePoints.length; i++) {
  6816. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6817. }
  6818. var continuedCurve = new Curve3(continuedPoints);
  6819. return continuedCurve;
  6820. };
  6821. Curve3.prototype._computeLength = function (path) {
  6822. var l = 0;
  6823. for (var i = 1; i < path.length; i++) {
  6824. l += (path[i].subtract(path[i - 1])).length();
  6825. }
  6826. return l;
  6827. };
  6828. return Curve3;
  6829. }());
  6830. BABYLON.Curve3 = Curve3;
  6831. // Vertex formats
  6832. var PositionNormalVertex = /** @class */ (function () {
  6833. function PositionNormalVertex(position, normal) {
  6834. if (position === void 0) { position = Vector3.Zero(); }
  6835. if (normal === void 0) { normal = Vector3.Up(); }
  6836. this.position = position;
  6837. this.normal = normal;
  6838. }
  6839. PositionNormalVertex.prototype.clone = function () {
  6840. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6841. };
  6842. return PositionNormalVertex;
  6843. }());
  6844. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6845. var PositionNormalTextureVertex = /** @class */ (function () {
  6846. function PositionNormalTextureVertex(position, normal, uv) {
  6847. if (position === void 0) { position = Vector3.Zero(); }
  6848. if (normal === void 0) { normal = Vector3.Up(); }
  6849. if (uv === void 0) { uv = Vector2.Zero(); }
  6850. this.position = position;
  6851. this.normal = normal;
  6852. this.uv = uv;
  6853. }
  6854. PositionNormalTextureVertex.prototype.clone = function () {
  6855. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6856. };
  6857. return PositionNormalTextureVertex;
  6858. }());
  6859. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6860. // Temporary pre-allocated objects for engine internal use
  6861. // usage in any internal function :
  6862. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6863. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6864. var Tmp = /** @class */ (function () {
  6865. function Tmp() {
  6866. }
  6867. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6868. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6869. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6870. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6871. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6872. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6873. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6874. Matrix.Zero(), Matrix.Zero(),
  6875. Matrix.Zero(), Matrix.Zero(),
  6876. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6877. return Tmp;
  6878. }());
  6879. BABYLON.Tmp = Tmp;
  6880. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6881. var MathTmp = /** @class */ (function () {
  6882. function MathTmp() {
  6883. }
  6884. MathTmp.Vector3 = [Vector3.Zero()];
  6885. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6886. MathTmp.Quaternion = [Quaternion.Zero()];
  6887. return MathTmp;
  6888. }());
  6889. })(BABYLON || (BABYLON = {}));
  6890. //# sourceMappingURL=babylon.math.js.map
  6891. "use strict";
  6892. var BABYLON;
  6893. (function (BABYLON) {
  6894. var Scalar = /** @class */ (function () {
  6895. function Scalar() {
  6896. }
  6897. /**
  6898. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6899. */
  6900. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6901. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6902. var num = a - b;
  6903. return -epsilon <= num && num <= epsilon;
  6904. };
  6905. /**
  6906. * Returns a string : the upper case translation of the number i to hexadecimal.
  6907. */
  6908. Scalar.ToHex = function (i) {
  6909. var str = i.toString(16);
  6910. if (i <= 15) {
  6911. return ("0" + str).toUpperCase();
  6912. }
  6913. return str.toUpperCase();
  6914. };
  6915. /**
  6916. * Returns -1 if value is negative and +1 is value is positive.
  6917. * Returns the value itself if it's equal to zero.
  6918. */
  6919. Scalar.Sign = function (value) {
  6920. value = +value; // convert to a number
  6921. if (value === 0 || isNaN(value))
  6922. return value;
  6923. return value > 0 ? 1 : -1;
  6924. };
  6925. /**
  6926. * Returns the value itself if it's between min and max.
  6927. * Returns min if the value is lower than min.
  6928. * Returns max if the value is greater than max.
  6929. */
  6930. Scalar.Clamp = function (value, min, max) {
  6931. if (min === void 0) { min = 0; }
  6932. if (max === void 0) { max = 1; }
  6933. return Math.min(max, Math.max(min, value));
  6934. };
  6935. /**
  6936. * Returns the log2 of value.
  6937. */
  6938. Scalar.Log2 = function (value) {
  6939. return Math.log(value) * Math.LOG2E;
  6940. };
  6941. /**
  6942. * Loops the value, so that it is never larger than length and never smaller than 0.
  6943. *
  6944. * This is similar to the modulo operator but it works with floating point numbers.
  6945. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6946. * With t = 5 and length = 2.5, the result would be 0.0.
  6947. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6948. */
  6949. Scalar.Repeat = function (value, length) {
  6950. return value - Math.floor(value / length) * length;
  6951. };
  6952. /**
  6953. * Normalize the value between 0.0 and 1.0 using min and max values
  6954. */
  6955. Scalar.Normalize = function (value, min, max) {
  6956. return (value - min) / (max - min);
  6957. };
  6958. /**
  6959. * Denormalize the value from 0.0 and 1.0 using min and max values
  6960. */
  6961. Scalar.Denormalize = function (normalized, min, max) {
  6962. return (normalized * (max - min) + min);
  6963. };
  6964. /**
  6965. * Calculates the shortest difference between two given angles given in degrees.
  6966. */
  6967. Scalar.DeltaAngle = function (current, target) {
  6968. var num = Scalar.Repeat(target - current, 360.0);
  6969. if (num > 180.0) {
  6970. num -= 360.0;
  6971. }
  6972. return num;
  6973. };
  6974. /**
  6975. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6976. *
  6977. * The returned value will move back and forth between 0 and length
  6978. */
  6979. Scalar.PingPong = function (tx, length) {
  6980. var t = Scalar.Repeat(tx, length * 2.0);
  6981. return length - Math.abs(t - length);
  6982. };
  6983. /**
  6984. * Interpolates between min and max with smoothing at the limits.
  6985. *
  6986. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6987. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6988. */
  6989. Scalar.SmoothStep = function (from, to, tx) {
  6990. var t = Scalar.Clamp(tx);
  6991. t = -2.0 * t * t * t + 3.0 * t * t;
  6992. return to * t + from * (1.0 - t);
  6993. };
  6994. /**
  6995. * Moves a value current towards target.
  6996. *
  6997. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6998. * Negative values of maxDelta pushes the value away from target.
  6999. */
  7000. Scalar.MoveTowards = function (current, target, maxDelta) {
  7001. var result = 0;
  7002. if (Math.abs(target - current) <= maxDelta) {
  7003. result = target;
  7004. }
  7005. else {
  7006. result = current + Scalar.Sign(target - current) * maxDelta;
  7007. }
  7008. return result;
  7009. };
  7010. /**
  7011. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7012. *
  7013. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7014. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7015. */
  7016. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7017. var num = Scalar.DeltaAngle(current, target);
  7018. var result = 0;
  7019. if (-maxDelta < num && num < maxDelta) {
  7020. result = target;
  7021. }
  7022. else {
  7023. target = current + num;
  7024. result = Scalar.MoveTowards(current, target, maxDelta);
  7025. }
  7026. return result;
  7027. };
  7028. /**
  7029. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7030. */
  7031. Scalar.Lerp = function (start, end, amount) {
  7032. return start + ((end - start) * amount);
  7033. };
  7034. /**
  7035. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7036. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7037. */
  7038. Scalar.LerpAngle = function (start, end, amount) {
  7039. var num = Scalar.Repeat(end - start, 360.0);
  7040. if (num > 180.0) {
  7041. num -= 360.0;
  7042. }
  7043. return start + num * Scalar.Clamp(amount);
  7044. };
  7045. /**
  7046. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7047. */
  7048. Scalar.InverseLerp = function (a, b, value) {
  7049. var result = 0;
  7050. if (a != b) {
  7051. result = Scalar.Clamp((value - a) / (b - a));
  7052. }
  7053. else {
  7054. result = 0.0;
  7055. }
  7056. return result;
  7057. };
  7058. /**
  7059. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7060. */
  7061. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7062. var squared = amount * amount;
  7063. var cubed = amount * squared;
  7064. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7065. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7066. var part3 = (cubed - (2.0 * squared)) + amount;
  7067. var part4 = cubed - squared;
  7068. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7069. };
  7070. /**
  7071. * Returns a random float number between and min and max values
  7072. */
  7073. Scalar.RandomRange = function (min, max) {
  7074. if (min === max)
  7075. return min;
  7076. return ((Math.random() * (max - min)) + min);
  7077. };
  7078. /**
  7079. * This function returns percentage of a number in a given range.
  7080. *
  7081. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7082. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7083. */
  7084. Scalar.RangeToPercent = function (number, min, max) {
  7085. return ((number - min) / (max - min));
  7086. };
  7087. /**
  7088. * This function returns number that corresponds to the percentage in a given range.
  7089. *
  7090. * PercentToRange(0.34,0,100) will return 34.
  7091. */
  7092. Scalar.PercentToRange = function (percent, min, max) {
  7093. return ((max - min) * percent + min);
  7094. };
  7095. /**
  7096. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7097. * @param angle The angle to normalize in radian.
  7098. * @return The converted angle.
  7099. */
  7100. Scalar.NormalizeRadians = function (angle) {
  7101. // More precise but slower version kept for reference.
  7102. // angle = angle % Tools.TwoPi;
  7103. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7104. //if (angle > Math.PI) {
  7105. // angle -= Tools.TwoPi;
  7106. //}
  7107. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7108. return angle;
  7109. };
  7110. /**
  7111. * Two pi constants convenient for computation.
  7112. */
  7113. Scalar.TwoPi = Math.PI * 2;
  7114. return Scalar;
  7115. }());
  7116. BABYLON.Scalar = Scalar;
  7117. })(BABYLON || (BABYLON = {}));
  7118. //# sourceMappingURL=babylon.math.scalar.js.map
  7119. "use strict";
  7120. //# sourceMappingURL=babylon.mixins.js.map
  7121. "use strict";
  7122. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7123. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7124. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7125. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7126. //# sourceMappingURL=babylon.webgl2.js.map
  7127. "use strict";
  7128. var BABYLON;
  7129. (function (BABYLON) {
  7130. var __decoratorInitialStore = {};
  7131. var __mergedStore = {};
  7132. var _copySource = function (creationFunction, source, instanciate) {
  7133. var destination = creationFunction();
  7134. // Tags
  7135. if (BABYLON.Tags) {
  7136. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7137. }
  7138. var classStore = getMergedStore(destination);
  7139. // Properties
  7140. for (var property in classStore) {
  7141. var propertyDescriptor = classStore[property];
  7142. var sourceProperty = source[property];
  7143. var propertyType = propertyDescriptor.type;
  7144. if (sourceProperty !== undefined && sourceProperty !== null) {
  7145. switch (propertyType) {
  7146. case 0: // Value
  7147. case 6:// Mesh reference
  7148. destination[property] = sourceProperty;
  7149. break;
  7150. case 1:// Texture
  7151. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7152. break;
  7153. case 2: // Color3
  7154. case 3: // FresnelParameters
  7155. case 4: // Vector2
  7156. case 5: // Vector3
  7157. case 7: // Color Curves
  7158. case 10:// Quaternion
  7159. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7160. break;
  7161. }
  7162. }
  7163. }
  7164. return destination;
  7165. };
  7166. function getDirectStore(target) {
  7167. var classKey = target.getClassName();
  7168. if (!__decoratorInitialStore[classKey]) {
  7169. __decoratorInitialStore[classKey] = {};
  7170. }
  7171. return __decoratorInitialStore[classKey];
  7172. }
  7173. /**
  7174. * Return the list of properties flagged as serializable
  7175. * @param target: host object
  7176. */
  7177. function getMergedStore(target) {
  7178. var classKey = target.getClassName();
  7179. if (__mergedStore[classKey]) {
  7180. return __mergedStore[classKey];
  7181. }
  7182. __mergedStore[classKey] = {};
  7183. var store = __mergedStore[classKey];
  7184. var currentTarget = target;
  7185. var currentKey = classKey;
  7186. while (currentKey) {
  7187. var initialStore = __decoratorInitialStore[currentKey];
  7188. for (var property in initialStore) {
  7189. store[property] = initialStore[property];
  7190. }
  7191. var parent_1 = void 0;
  7192. var done = false;
  7193. do {
  7194. parent_1 = Object.getPrototypeOf(currentTarget);
  7195. if (!parent_1.getClassName) {
  7196. done = true;
  7197. break;
  7198. }
  7199. if (parent_1.getClassName() !== currentKey) {
  7200. break;
  7201. }
  7202. currentTarget = parent_1;
  7203. } while (parent_1);
  7204. if (done) {
  7205. break;
  7206. }
  7207. currentKey = parent_1.getClassName();
  7208. currentTarget = parent_1;
  7209. }
  7210. return store;
  7211. }
  7212. function generateSerializableMember(type, sourceName) {
  7213. return function (target, propertyKey) {
  7214. var classStore = getDirectStore(target);
  7215. if (!classStore[propertyKey]) {
  7216. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7217. }
  7218. };
  7219. }
  7220. function generateExpandMember(setCallback, targetKey) {
  7221. if (targetKey === void 0) { targetKey = null; }
  7222. return function (target, propertyKey) {
  7223. var key = targetKey || ("_" + propertyKey);
  7224. Object.defineProperty(target, propertyKey, {
  7225. get: function () {
  7226. return this[key];
  7227. },
  7228. set: function (value) {
  7229. if (this[key] === value) {
  7230. return;
  7231. }
  7232. this[key] = value;
  7233. target[setCallback].apply(this);
  7234. },
  7235. enumerable: true,
  7236. configurable: true
  7237. });
  7238. };
  7239. }
  7240. function expandToProperty(callback, targetKey) {
  7241. if (targetKey === void 0) { targetKey = null; }
  7242. return generateExpandMember(callback, targetKey);
  7243. }
  7244. BABYLON.expandToProperty = expandToProperty;
  7245. function serialize(sourceName) {
  7246. return generateSerializableMember(0, sourceName); // value member
  7247. }
  7248. BABYLON.serialize = serialize;
  7249. function serializeAsTexture(sourceName) {
  7250. return generateSerializableMember(1, sourceName); // texture member
  7251. }
  7252. BABYLON.serializeAsTexture = serializeAsTexture;
  7253. function serializeAsColor3(sourceName) {
  7254. return generateSerializableMember(2, sourceName); // color3 member
  7255. }
  7256. BABYLON.serializeAsColor3 = serializeAsColor3;
  7257. function serializeAsFresnelParameters(sourceName) {
  7258. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7259. }
  7260. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7261. function serializeAsVector2(sourceName) {
  7262. return generateSerializableMember(4, sourceName); // vector2 member
  7263. }
  7264. BABYLON.serializeAsVector2 = serializeAsVector2;
  7265. function serializeAsVector3(sourceName) {
  7266. return generateSerializableMember(5, sourceName); // vector3 member
  7267. }
  7268. BABYLON.serializeAsVector3 = serializeAsVector3;
  7269. function serializeAsMeshReference(sourceName) {
  7270. return generateSerializableMember(6, sourceName); // mesh reference member
  7271. }
  7272. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7273. function serializeAsColorCurves(sourceName) {
  7274. return generateSerializableMember(7, sourceName); // color curves
  7275. }
  7276. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7277. function serializeAsColor4(sourceName) {
  7278. return generateSerializableMember(8, sourceName); // color 4
  7279. }
  7280. BABYLON.serializeAsColor4 = serializeAsColor4;
  7281. function serializeAsImageProcessingConfiguration(sourceName) {
  7282. return generateSerializableMember(9, sourceName); // image processing
  7283. }
  7284. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7285. function serializeAsQuaternion(sourceName) {
  7286. return generateSerializableMember(10, sourceName); // quaternion member
  7287. }
  7288. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7289. var SerializationHelper = /** @class */ (function () {
  7290. function SerializationHelper() {
  7291. }
  7292. SerializationHelper.Serialize = function (entity, serializationObject) {
  7293. if (!serializationObject) {
  7294. serializationObject = {};
  7295. }
  7296. // Tags
  7297. if (BABYLON.Tags) {
  7298. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7299. }
  7300. var serializedProperties = getMergedStore(entity);
  7301. // Properties
  7302. for (var property in serializedProperties) {
  7303. var propertyDescriptor = serializedProperties[property];
  7304. var targetPropertyName = propertyDescriptor.sourceName || property;
  7305. var propertyType = propertyDescriptor.type;
  7306. var sourceProperty = entity[property];
  7307. if (sourceProperty !== undefined && sourceProperty !== null) {
  7308. switch (propertyType) {
  7309. case 0:// Value
  7310. serializationObject[targetPropertyName] = sourceProperty;
  7311. break;
  7312. case 1:// Texture
  7313. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7314. break;
  7315. case 2:// Color3
  7316. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7317. break;
  7318. case 3:// FresnelParameters
  7319. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7320. break;
  7321. case 4:// Vector2
  7322. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7323. break;
  7324. case 5:// Vector3
  7325. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7326. break;
  7327. case 6:// Mesh reference
  7328. serializationObject[targetPropertyName] = sourceProperty.id;
  7329. break;
  7330. case 7:// Color Curves
  7331. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7332. break;
  7333. case 8:// Color 4
  7334. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7335. break;
  7336. case 9:// Image Processing
  7337. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7338. break;
  7339. }
  7340. }
  7341. }
  7342. return serializationObject;
  7343. };
  7344. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7345. if (rootUrl === void 0) { rootUrl = null; }
  7346. var destination = creationFunction();
  7347. if (!rootUrl) {
  7348. rootUrl = "";
  7349. }
  7350. // Tags
  7351. if (BABYLON.Tags) {
  7352. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7353. }
  7354. var classStore = getMergedStore(destination);
  7355. // Properties
  7356. for (var property in classStore) {
  7357. var propertyDescriptor = classStore[property];
  7358. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7359. var propertyType = propertyDescriptor.type;
  7360. if (sourceProperty !== undefined && sourceProperty !== null) {
  7361. var dest = destination;
  7362. switch (propertyType) {
  7363. case 0:// Value
  7364. dest[property] = sourceProperty;
  7365. break;
  7366. case 1:// Texture
  7367. if (scene) {
  7368. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7369. }
  7370. break;
  7371. case 2:// Color3
  7372. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7373. break;
  7374. case 3:// FresnelParameters
  7375. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7376. break;
  7377. case 4:// Vector2
  7378. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7379. break;
  7380. case 5:// Vector3
  7381. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7382. break;
  7383. case 6:// Mesh reference
  7384. if (scene) {
  7385. dest[property] = scene.getLastMeshByID(sourceProperty);
  7386. }
  7387. break;
  7388. case 7:// Color Curves
  7389. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7390. break;
  7391. case 8:// Color 4
  7392. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7393. break;
  7394. case 9:// Image Processing
  7395. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7396. break;
  7397. }
  7398. }
  7399. }
  7400. return destination;
  7401. };
  7402. SerializationHelper.Clone = function (creationFunction, source) {
  7403. return _copySource(creationFunction, source, false);
  7404. };
  7405. SerializationHelper.Instanciate = function (creationFunction, source) {
  7406. return _copySource(creationFunction, source, true);
  7407. };
  7408. return SerializationHelper;
  7409. }());
  7410. BABYLON.SerializationHelper = SerializationHelper;
  7411. })(BABYLON || (BABYLON = {}));
  7412. //# sourceMappingURL=babylon.decorators.js.map
  7413. "use strict";
  7414. var BABYLON;
  7415. (function (BABYLON) {
  7416. /**
  7417. * Wrapper class for promise with external resolve and reject.
  7418. */
  7419. var Deferred = /** @class */ (function () {
  7420. /**
  7421. * Constructor for this deferred object.
  7422. */
  7423. function Deferred() {
  7424. var _this = this;
  7425. this.promise = new Promise(function (resolve, reject) {
  7426. _this._resolve = resolve;
  7427. _this._reject = reject;
  7428. });
  7429. }
  7430. Object.defineProperty(Deferred.prototype, "resolve", {
  7431. /**
  7432. * The resolve method of the promise associated with this deferred object.
  7433. */
  7434. get: function () {
  7435. return this._resolve;
  7436. },
  7437. enumerable: true,
  7438. configurable: true
  7439. });
  7440. Object.defineProperty(Deferred.prototype, "reject", {
  7441. /**
  7442. * The reject method of the promise associated with this deferred object.
  7443. */
  7444. get: function () {
  7445. return this._reject;
  7446. },
  7447. enumerable: true,
  7448. configurable: true
  7449. });
  7450. return Deferred;
  7451. }());
  7452. BABYLON.Deferred = Deferred;
  7453. })(BABYLON || (BABYLON = {}));
  7454. //# sourceMappingURL=babylon.deferred.js.map
  7455. "use strict";
  7456. var BABYLON;
  7457. (function (BABYLON) {
  7458. /**
  7459. * A class serves as a medium between the observable and its observers
  7460. */
  7461. var EventState = /** @class */ (function () {
  7462. /**
  7463. * Create a new EventState
  7464. * @param mask defines the mask associated with this state
  7465. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7466. * @param target defines the original target of the state
  7467. * @param currentTarget defines the current target of the state
  7468. */
  7469. function EventState(mask, skipNextObservers, target, currentTarget) {
  7470. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7471. this.initalize(mask, skipNextObservers, target, currentTarget);
  7472. }
  7473. /**
  7474. * Initialize the current event state
  7475. * @param mask defines the mask associated with this state
  7476. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7477. * @param target defines the original target of the state
  7478. * @param currentTarget defines the current target of the state
  7479. * @returns the current event state
  7480. */
  7481. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7482. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7483. this.mask = mask;
  7484. this.skipNextObservers = skipNextObservers;
  7485. this.target = target;
  7486. this.currentTarget = currentTarget;
  7487. return this;
  7488. };
  7489. return EventState;
  7490. }());
  7491. BABYLON.EventState = EventState;
  7492. /**
  7493. * Represent an Observer registered to a given Observable object.
  7494. */
  7495. var Observer = /** @class */ (function () {
  7496. /**
  7497. * Creates a new observer
  7498. * @param callback defines the callback to call when the observer is notified
  7499. * @param mask defines the mask of the observer (used to filter notifications)
  7500. * @param scope defines the current scope used to restore the JS context
  7501. */
  7502. function Observer(
  7503. /**
  7504. * Defines the callback to call when the observer is notified
  7505. */
  7506. callback,
  7507. /**
  7508. * Defines the mask of the observer (used to filter notifications)
  7509. */
  7510. mask,
  7511. /**
  7512. * Defines the current scope used to restore the JS context
  7513. */
  7514. scope) {
  7515. if (scope === void 0) { scope = null; }
  7516. this.callback = callback;
  7517. this.mask = mask;
  7518. this.scope = scope;
  7519. /** @ignore */
  7520. this._willBeUnregistered = false;
  7521. /**
  7522. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7523. */
  7524. this.unregisterOnNextCall = false;
  7525. }
  7526. return Observer;
  7527. }());
  7528. BABYLON.Observer = Observer;
  7529. /**
  7530. * Represent a list of observers registered to multiple Observables object.
  7531. */
  7532. var MultiObserver = /** @class */ (function () {
  7533. function MultiObserver() {
  7534. }
  7535. /**
  7536. * Release associated resources
  7537. */
  7538. MultiObserver.prototype.dispose = function () {
  7539. if (this._observers && this._observables) {
  7540. for (var index = 0; index < this._observers.length; index++) {
  7541. this._observables[index].remove(this._observers[index]);
  7542. }
  7543. }
  7544. this._observers = null;
  7545. this._observables = null;
  7546. };
  7547. /**
  7548. * Raise a callback when one of the observable will notify
  7549. * @param observables defines a list of observables to watch
  7550. * @param callback defines the callback to call on notification
  7551. * @param mask defines the mask used to filter notifications
  7552. * @param scope defines the current scope used to restore the JS context
  7553. * @returns the new MultiObserver
  7554. */
  7555. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7556. if (mask === void 0) { mask = -1; }
  7557. if (scope === void 0) { scope = null; }
  7558. var result = new MultiObserver();
  7559. result._observers = new Array();
  7560. result._observables = observables;
  7561. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7562. var observable = observables_1[_i];
  7563. var observer = observable.add(callback, mask, false, scope);
  7564. if (observer) {
  7565. result._observers.push(observer);
  7566. }
  7567. }
  7568. return result;
  7569. };
  7570. return MultiObserver;
  7571. }());
  7572. BABYLON.MultiObserver = MultiObserver;
  7573. /**
  7574. * The Observable class is a simple implementation of the Observable pattern.
  7575. * 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.
  7576. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7577. * 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).
  7578. * 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.
  7579. */
  7580. var Observable = /** @class */ (function () {
  7581. /**
  7582. * Creates a new observable
  7583. * @param onObserverAdded defines a callback to call when a new observer is added
  7584. */
  7585. function Observable(onObserverAdded) {
  7586. this._observers = new Array();
  7587. this._eventState = new EventState(0);
  7588. if (onObserverAdded) {
  7589. this._onObserverAdded = onObserverAdded;
  7590. }
  7591. }
  7592. /**
  7593. * Create a new Observer with the specified callback
  7594. * @param callback the callback that will be executed for that Observer
  7595. * @param mask the mask used to filter observers
  7596. * @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.
  7597. * @param scope optional scope for the callback to be called from
  7598. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7599. * @returns the new observer created for the callback
  7600. */
  7601. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7602. if (mask === void 0) { mask = -1; }
  7603. if (insertFirst === void 0) { insertFirst = false; }
  7604. if (scope === void 0) { scope = null; }
  7605. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7606. if (!callback) {
  7607. return null;
  7608. }
  7609. var observer = new Observer(callback, mask, scope);
  7610. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7611. if (insertFirst) {
  7612. this._observers.unshift(observer);
  7613. }
  7614. else {
  7615. this._observers.push(observer);
  7616. }
  7617. if (this._onObserverAdded) {
  7618. this._onObserverAdded(observer);
  7619. }
  7620. return observer;
  7621. };
  7622. /**
  7623. * Remove an Observer from the Observable object
  7624. * @param observer the instance of the Observer to remove
  7625. * @returns false if it doesn't belong to this Observable
  7626. */
  7627. Observable.prototype.remove = function (observer) {
  7628. if (!observer) {
  7629. return false;
  7630. }
  7631. var index = this._observers.indexOf(observer);
  7632. if (index !== -1) {
  7633. this._observers.splice(index, 1);
  7634. return true;
  7635. }
  7636. return false;
  7637. };
  7638. /**
  7639. * Remove a callback from the Observable object
  7640. * @param callback the callback to remove
  7641. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7642. * @returns false if it doesn't belong to this Observable
  7643. */
  7644. Observable.prototype.removeCallback = function (callback, scope) {
  7645. for (var index = 0; index < this._observers.length; index++) {
  7646. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7647. this._observers.splice(index, 1);
  7648. return true;
  7649. }
  7650. }
  7651. return false;
  7652. };
  7653. Observable.prototype._deferUnregister = function (observer) {
  7654. var _this = this;
  7655. observer.unregisterOnNextCall = false;
  7656. observer._willBeUnregistered = true;
  7657. BABYLON.Tools.SetImmediate(function () {
  7658. _this.remove(observer);
  7659. });
  7660. };
  7661. /**
  7662. * Notify all Observers by calling their respective callback with the given data
  7663. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7664. * @param eventData defines the data to send to all observers
  7665. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7666. * @param target defines the original target of the state
  7667. * @param currentTarget defines the current target of the state
  7668. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7669. */
  7670. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7671. if (mask === void 0) { mask = -1; }
  7672. if (!this._observers.length) {
  7673. return true;
  7674. }
  7675. var state = this._eventState;
  7676. state.mask = mask;
  7677. state.target = target;
  7678. state.currentTarget = currentTarget;
  7679. state.skipNextObservers = false;
  7680. state.lastReturnValue = eventData;
  7681. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7682. var obs = _a[_i];
  7683. if (obs._willBeUnregistered) {
  7684. continue;
  7685. }
  7686. if (obs.mask & mask) {
  7687. if (obs.scope) {
  7688. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7689. }
  7690. else {
  7691. state.lastReturnValue = obs.callback(eventData, state);
  7692. }
  7693. if (obs.unregisterOnNextCall) {
  7694. this._deferUnregister(obs);
  7695. }
  7696. }
  7697. if (state.skipNextObservers) {
  7698. return false;
  7699. }
  7700. }
  7701. return true;
  7702. };
  7703. /**
  7704. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7705. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7706. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7707. * and it is crucial that all callbacks will be executed.
  7708. * The order of the callbacks is kept, callbacks are not executed parallel.
  7709. *
  7710. * @param eventData The data to be sent to each callback
  7711. * @param mask is used to filter observers defaults to -1
  7712. * @param target defines the callback target (see EventState)
  7713. * @param currentTarget defines he current object in the bubbling phase
  7714. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7715. */
  7716. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7717. var _this = this;
  7718. if (mask === void 0) { mask = -1; }
  7719. // create an empty promise
  7720. var p = Promise.resolve(eventData);
  7721. // no observers? return this promise.
  7722. if (!this._observers.length) {
  7723. return p;
  7724. }
  7725. var state = this._eventState;
  7726. state.mask = mask;
  7727. state.target = target;
  7728. state.currentTarget = currentTarget;
  7729. state.skipNextObservers = false;
  7730. // execute one callback after another (not using Promise.all, the order is important)
  7731. this._observers.forEach(function (obs) {
  7732. if (state.skipNextObservers) {
  7733. return;
  7734. }
  7735. if (obs._willBeUnregistered) {
  7736. return;
  7737. }
  7738. if (obs.mask & mask) {
  7739. if (obs.scope) {
  7740. p = p.then(function (lastReturnedValue) {
  7741. state.lastReturnValue = lastReturnedValue;
  7742. return obs.callback.apply(obs.scope, [eventData, state]);
  7743. });
  7744. }
  7745. else {
  7746. p = p.then(function (lastReturnedValue) {
  7747. state.lastReturnValue = lastReturnedValue;
  7748. return obs.callback(eventData, state);
  7749. });
  7750. }
  7751. if (obs.unregisterOnNextCall) {
  7752. _this._deferUnregister(obs);
  7753. }
  7754. }
  7755. });
  7756. // return the eventData
  7757. return p.then(function () { return eventData; });
  7758. };
  7759. /**
  7760. * Notify a specific observer
  7761. * @param observer defines the observer to notify
  7762. * @param eventData defines the data to be sent to each callback
  7763. * @param mask is used to filter observers defaults to -1
  7764. */
  7765. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7766. if (mask === void 0) { mask = -1; }
  7767. var state = this._eventState;
  7768. state.mask = mask;
  7769. state.skipNextObservers = false;
  7770. observer.callback(eventData, state);
  7771. };
  7772. /**
  7773. * Gets a boolean indicating if the observable has at least one observer
  7774. * @returns true is the Observable has at least one Observer registered
  7775. */
  7776. Observable.prototype.hasObservers = function () {
  7777. return this._observers.length > 0;
  7778. };
  7779. /**
  7780. * Clear the list of observers
  7781. */
  7782. Observable.prototype.clear = function () {
  7783. this._observers = new Array();
  7784. this._onObserverAdded = null;
  7785. };
  7786. /**
  7787. * Clone the current observable
  7788. * @returns a new observable
  7789. */
  7790. Observable.prototype.clone = function () {
  7791. var result = new Observable();
  7792. result._observers = this._observers.slice(0);
  7793. return result;
  7794. };
  7795. /**
  7796. * Does this observable handles observer registered with a given mask
  7797. * @param mask defines the mask to be tested
  7798. * @return whether or not one observer registered with the given mask is handeled
  7799. **/
  7800. Observable.prototype.hasSpecificMask = function (mask) {
  7801. if (mask === void 0) { mask = -1; }
  7802. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7803. var obs = _a[_i];
  7804. if (obs.mask & mask || obs.mask === mask) {
  7805. return true;
  7806. }
  7807. }
  7808. return false;
  7809. };
  7810. return Observable;
  7811. }());
  7812. BABYLON.Observable = Observable;
  7813. })(BABYLON || (BABYLON = {}));
  7814. //# sourceMappingURL=babylon.observable.js.map
  7815. "use strict";
  7816. var BABYLON;
  7817. (function (BABYLON) {
  7818. var SmartArray = /** @class */ (function () {
  7819. function SmartArray(capacity) {
  7820. this.length = 0;
  7821. this.data = new Array(capacity);
  7822. this._id = SmartArray._GlobalId++;
  7823. }
  7824. SmartArray.prototype.push = function (value) {
  7825. this.data[this.length++] = value;
  7826. if (this.length > this.data.length) {
  7827. this.data.length *= 2;
  7828. }
  7829. };
  7830. SmartArray.prototype.forEach = function (func) {
  7831. for (var index = 0; index < this.length; index++) {
  7832. func(this.data[index]);
  7833. }
  7834. };
  7835. SmartArray.prototype.sort = function (compareFn) {
  7836. this.data.sort(compareFn);
  7837. };
  7838. SmartArray.prototype.reset = function () {
  7839. this.length = 0;
  7840. };
  7841. SmartArray.prototype.dispose = function () {
  7842. this.reset();
  7843. if (this.data) {
  7844. this.data.length = 0;
  7845. this.data = [];
  7846. }
  7847. };
  7848. SmartArray.prototype.concat = function (array) {
  7849. if (array.length === 0) {
  7850. return;
  7851. }
  7852. if (this.length + array.length > this.data.length) {
  7853. this.data.length = (this.length + array.length) * 2;
  7854. }
  7855. for (var index = 0; index < array.length; index++) {
  7856. this.data[this.length++] = (array.data || array)[index];
  7857. }
  7858. };
  7859. SmartArray.prototype.indexOf = function (value) {
  7860. var position = this.data.indexOf(value);
  7861. if (position >= this.length) {
  7862. return -1;
  7863. }
  7864. return position;
  7865. };
  7866. SmartArray.prototype.contains = function (value) {
  7867. return this.data.indexOf(value) !== -1;
  7868. };
  7869. // Statics
  7870. SmartArray._GlobalId = 0;
  7871. return SmartArray;
  7872. }());
  7873. BABYLON.SmartArray = SmartArray;
  7874. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7875. __extends(SmartArrayNoDuplicate, _super);
  7876. function SmartArrayNoDuplicate() {
  7877. var _this = _super !== null && _super.apply(this, arguments) || this;
  7878. _this._duplicateId = 0;
  7879. return _this;
  7880. }
  7881. SmartArrayNoDuplicate.prototype.push = function (value) {
  7882. _super.prototype.push.call(this, value);
  7883. if (!value.__smartArrayFlags) {
  7884. value.__smartArrayFlags = {};
  7885. }
  7886. value.__smartArrayFlags[this._id] = this._duplicateId;
  7887. };
  7888. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7889. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7890. return false;
  7891. }
  7892. this.push(value);
  7893. return true;
  7894. };
  7895. SmartArrayNoDuplicate.prototype.reset = function () {
  7896. _super.prototype.reset.call(this);
  7897. this._duplicateId++;
  7898. };
  7899. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7900. if (array.length === 0) {
  7901. return;
  7902. }
  7903. if (this.length + array.length > this.data.length) {
  7904. this.data.length = (this.length + array.length) * 2;
  7905. }
  7906. for (var index = 0; index < array.length; index++) {
  7907. var item = (array.data || array)[index];
  7908. this.pushNoDuplicate(item);
  7909. }
  7910. };
  7911. return SmartArrayNoDuplicate;
  7912. }(SmartArray));
  7913. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7914. })(BABYLON || (BABYLON = {}));
  7915. //# sourceMappingURL=babylon.smartArray.js.map
  7916. "use strict";
  7917. var BABYLON;
  7918. (function (BABYLON) {
  7919. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7920. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7921. var LoadFileError = /** @class */ (function (_super) {
  7922. __extends(LoadFileError, _super);
  7923. function LoadFileError(message, request) {
  7924. var _this = _super.call(this, message) || this;
  7925. _this.request = request;
  7926. _this.name = "LoadFileError";
  7927. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7928. return _this;
  7929. }
  7930. // Polyfill for Object.setPrototypeOf if necessary.
  7931. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7932. return LoadFileError;
  7933. }(Error));
  7934. BABYLON.LoadFileError = LoadFileError;
  7935. var RetryStrategy = /** @class */ (function () {
  7936. function RetryStrategy() {
  7937. }
  7938. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7939. if (maxRetries === void 0) { maxRetries = 3; }
  7940. if (baseInterval === void 0) { baseInterval = 500; }
  7941. return function (url, request, retryIndex) {
  7942. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7943. return -1;
  7944. }
  7945. return Math.pow(2, retryIndex) * baseInterval;
  7946. };
  7947. };
  7948. return RetryStrategy;
  7949. }());
  7950. BABYLON.RetryStrategy = RetryStrategy;
  7951. // Screenshots
  7952. var screenshotCanvas;
  7953. var cloneValue = function (source, destinationObject) {
  7954. if (!source)
  7955. return null;
  7956. if (source instanceof BABYLON.Mesh) {
  7957. return null;
  7958. }
  7959. if (source instanceof BABYLON.SubMesh) {
  7960. return source.clone(destinationObject);
  7961. }
  7962. else if (source.clone) {
  7963. return source.clone();
  7964. }
  7965. return null;
  7966. };
  7967. var Tools = /** @class */ (function () {
  7968. function Tools() {
  7969. }
  7970. /**
  7971. * Interpolates between a and b via alpha
  7972. * @param a The lower value (returned when alpha = 0)
  7973. * @param b The upper value (returned when alpha = 1)
  7974. * @param alpha The interpolation-factor
  7975. * @return The mixed value
  7976. */
  7977. Tools.Mix = function (a, b, alpha) {
  7978. return a * (1 - alpha) + b * alpha;
  7979. };
  7980. Tools.Instantiate = function (className) {
  7981. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7982. return Tools.RegisteredExternalClasses[className];
  7983. }
  7984. var arr = className.split(".");
  7985. var fn = (window || this);
  7986. for (var i = 0, len = arr.length; i < len; i++) {
  7987. fn = fn[arr[i]];
  7988. }
  7989. if (typeof fn !== "function") {
  7990. return null;
  7991. }
  7992. return fn;
  7993. };
  7994. /**
  7995. * Provides a slice function that will work even on IE
  7996. * @param data defines the array to slice
  7997. * @returns the new sliced array
  7998. */
  7999. Tools.Slice = function (data) {
  8000. if (data.slice) {
  8001. return data.slice();
  8002. }
  8003. return Array.prototype.slice.call(data);
  8004. };
  8005. Tools.SetImmediate = function (action) {
  8006. if (window.setImmediate) {
  8007. window.setImmediate(action);
  8008. }
  8009. else {
  8010. setTimeout(action, 1);
  8011. }
  8012. };
  8013. Tools.IsExponentOfTwo = function (value) {
  8014. var count = 1;
  8015. do {
  8016. count *= 2;
  8017. } while (count < value);
  8018. return count === value;
  8019. };
  8020. /**
  8021. * Find the next highest power of two.
  8022. * @param x Number to start search from.
  8023. * @return Next highest power of two.
  8024. */
  8025. Tools.CeilingPOT = function (x) {
  8026. x--;
  8027. x |= x >> 1;
  8028. x |= x >> 2;
  8029. x |= x >> 4;
  8030. x |= x >> 8;
  8031. x |= x >> 16;
  8032. x++;
  8033. return x;
  8034. };
  8035. /**
  8036. * Find the next lowest power of two.
  8037. * @param x Number to start search from.
  8038. * @return Next lowest power of two.
  8039. */
  8040. Tools.FloorPOT = function (x) {
  8041. x = x | (x >> 1);
  8042. x = x | (x >> 2);
  8043. x = x | (x >> 4);
  8044. x = x | (x >> 8);
  8045. x = x | (x >> 16);
  8046. return x - (x >> 1);
  8047. };
  8048. /**
  8049. * Find the nearest power of two.
  8050. * @param x Number to start search from.
  8051. * @return Next nearest power of two.
  8052. */
  8053. Tools.NearestPOT = function (x) {
  8054. var c = Tools.CeilingPOT(x);
  8055. var f = Tools.FloorPOT(x);
  8056. return (c - x) > (x - f) ? f : c;
  8057. };
  8058. Tools.GetExponentOfTwo = function (value, max, mode) {
  8059. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8060. var pot;
  8061. switch (mode) {
  8062. case BABYLON.Engine.SCALEMODE_FLOOR:
  8063. pot = Tools.FloorPOT(value);
  8064. break;
  8065. case BABYLON.Engine.SCALEMODE_NEAREST:
  8066. pot = Tools.NearestPOT(value);
  8067. break;
  8068. case BABYLON.Engine.SCALEMODE_CEILING:
  8069. default:
  8070. pot = Tools.CeilingPOT(value);
  8071. break;
  8072. }
  8073. return Math.min(pot, max);
  8074. };
  8075. Tools.GetFilename = function (path) {
  8076. var index = path.lastIndexOf("/");
  8077. if (index < 0)
  8078. return path;
  8079. return path.substring(index + 1);
  8080. };
  8081. /**
  8082. * Extracts the "folder" part of a path (everything before the filename).
  8083. * @param uri The URI to extract the info from
  8084. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8085. * @returns The "folder" part of the path
  8086. */
  8087. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8088. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8089. var index = uri.lastIndexOf("/");
  8090. if (index < 0) {
  8091. if (returnUnchangedIfNoSlash) {
  8092. return uri;
  8093. }
  8094. return "";
  8095. }
  8096. return uri.substring(0, index + 1);
  8097. };
  8098. Tools.GetDOMTextContent = function (element) {
  8099. var result = "";
  8100. var child = element.firstChild;
  8101. while (child) {
  8102. if (child.nodeType === 3) {
  8103. result += child.textContent;
  8104. }
  8105. child = child.nextSibling;
  8106. }
  8107. return result;
  8108. };
  8109. Tools.ToDegrees = function (angle) {
  8110. return angle * 180 / Math.PI;
  8111. };
  8112. Tools.ToRadians = function (angle) {
  8113. return angle * Math.PI / 180;
  8114. };
  8115. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8116. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8117. var output = "";
  8118. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8119. var i = 0;
  8120. var bytes = new Uint8Array(buffer);
  8121. while (i < bytes.length) {
  8122. chr1 = bytes[i++];
  8123. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8124. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8125. enc1 = chr1 >> 2;
  8126. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8127. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8128. enc4 = chr3 & 63;
  8129. if (isNaN(chr2)) {
  8130. enc3 = enc4 = 64;
  8131. }
  8132. else if (isNaN(chr3)) {
  8133. enc4 = 64;
  8134. }
  8135. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8136. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8137. }
  8138. return "data:image/png;base64," + output;
  8139. };
  8140. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8141. if (bias === void 0) { bias = null; }
  8142. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8143. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8144. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8145. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8146. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8147. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8148. }
  8149. if (bias) {
  8150. minimum.x -= minimum.x * bias.x + bias.y;
  8151. minimum.y -= minimum.y * bias.x + bias.y;
  8152. minimum.z -= minimum.z * bias.x + bias.y;
  8153. maximum.x += maximum.x * bias.x + bias.y;
  8154. maximum.y += maximum.y * bias.x + bias.y;
  8155. maximum.z += maximum.z * bias.x + bias.y;
  8156. }
  8157. return {
  8158. minimum: minimum,
  8159. maximum: maximum
  8160. };
  8161. };
  8162. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8163. if (bias === void 0) { bias = null; }
  8164. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8165. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8166. if (!stride) {
  8167. stride = 3;
  8168. }
  8169. for (var index = start; index < start + count; index++) {
  8170. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8171. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8172. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8173. }
  8174. if (bias) {
  8175. minimum.x -= minimum.x * bias.x + bias.y;
  8176. minimum.y -= minimum.y * bias.x + bias.y;
  8177. minimum.z -= minimum.z * bias.x + bias.y;
  8178. maximum.x += maximum.x * bias.x + bias.y;
  8179. maximum.y += maximum.y * bias.x + bias.y;
  8180. maximum.z += maximum.z * bias.x + bias.y;
  8181. }
  8182. return {
  8183. minimum: minimum,
  8184. maximum: maximum
  8185. };
  8186. };
  8187. Tools.Vector2ArrayFeeder = function (array) {
  8188. return function (index) {
  8189. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8190. var length = isFloatArray ? array.length / 2 : array.length;
  8191. if (index >= length) {
  8192. return null;
  8193. }
  8194. if (isFloatArray) {
  8195. var fa = array;
  8196. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8197. }
  8198. var a = array;
  8199. return a[index];
  8200. };
  8201. };
  8202. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8203. if (bias === void 0) { bias = null; }
  8204. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8205. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8206. var i = 0;
  8207. var cur = feeder(i++);
  8208. while (cur) {
  8209. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8210. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8211. cur = feeder(i++);
  8212. }
  8213. if (bias) {
  8214. minimum.x -= minimum.x * bias.x + bias.y;
  8215. minimum.y -= minimum.y * bias.x + bias.y;
  8216. maximum.x += maximum.x * bias.x + bias.y;
  8217. maximum.y += maximum.y * bias.x + bias.y;
  8218. }
  8219. return {
  8220. minimum: minimum,
  8221. maximum: maximum
  8222. };
  8223. };
  8224. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8225. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8226. return null;
  8227. return Array.isArray(obj) ? obj : [obj];
  8228. };
  8229. // Misc.
  8230. Tools.GetPointerPrefix = function () {
  8231. var eventPrefix = "pointer";
  8232. // Check if pointer events are supported
  8233. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8234. eventPrefix = "mouse";
  8235. }
  8236. return eventPrefix;
  8237. };
  8238. /**
  8239. * @param func - the function to be called
  8240. * @param requester - the object that will request the next frame. Falls back to window.
  8241. */
  8242. Tools.QueueNewFrame = function (func, requester) {
  8243. if (!Tools.IsWindowObjectExist()) {
  8244. return setTimeout(func, 16);
  8245. }
  8246. if (!requester) {
  8247. requester = window;
  8248. }
  8249. if (requester.requestAnimationFrame) {
  8250. return requester.requestAnimationFrame(func);
  8251. }
  8252. else if (requester.msRequestAnimationFrame) {
  8253. return requester.msRequestAnimationFrame(func);
  8254. }
  8255. else if (requester.webkitRequestAnimationFrame) {
  8256. return requester.webkitRequestAnimationFrame(func);
  8257. }
  8258. else if (requester.mozRequestAnimationFrame) {
  8259. return requester.mozRequestAnimationFrame(func);
  8260. }
  8261. else if (requester.oRequestAnimationFrame) {
  8262. return requester.oRequestAnimationFrame(func);
  8263. }
  8264. else {
  8265. return window.setTimeout(func, 16);
  8266. }
  8267. };
  8268. Tools.RequestFullscreen = function (element) {
  8269. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8270. if (!requestFunction)
  8271. return;
  8272. requestFunction.call(element);
  8273. };
  8274. Tools.ExitFullscreen = function () {
  8275. if (document.exitFullscreen) {
  8276. document.exitFullscreen();
  8277. }
  8278. else if (document.mozCancelFullScreen) {
  8279. document.mozCancelFullScreen();
  8280. }
  8281. else if (document.webkitCancelFullScreen) {
  8282. document.webkitCancelFullScreen();
  8283. }
  8284. else if (document.msCancelFullScreen) {
  8285. document.msCancelFullScreen();
  8286. }
  8287. };
  8288. Tools.SetCorsBehavior = function (url, element) {
  8289. if (url && url.indexOf("data:") === 0) {
  8290. return;
  8291. }
  8292. if (Tools.CorsBehavior) {
  8293. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8294. element.crossOrigin = Tools.CorsBehavior;
  8295. }
  8296. else {
  8297. var result = Tools.CorsBehavior(url);
  8298. if (result) {
  8299. element.crossOrigin = result;
  8300. }
  8301. }
  8302. }
  8303. };
  8304. // External files
  8305. Tools.CleanUrl = function (url) {
  8306. url = url.replace(/#/mg, "%23");
  8307. return url;
  8308. };
  8309. Tools.LoadImage = function (url, onLoad, onError, database) {
  8310. if (url instanceof ArrayBuffer) {
  8311. url = Tools.EncodeArrayBufferTobase64(url);
  8312. }
  8313. url = Tools.CleanUrl(url);
  8314. url = Tools.PreprocessUrl(url);
  8315. var img = new Image();
  8316. Tools.SetCorsBehavior(url, img);
  8317. var loadHandler = function () {
  8318. img.removeEventListener("load", loadHandler);
  8319. img.removeEventListener("error", errorHandler);
  8320. onLoad(img);
  8321. };
  8322. var errorHandler = function (err) {
  8323. img.removeEventListener("load", loadHandler);
  8324. img.removeEventListener("error", errorHandler);
  8325. Tools.Error("Error while trying to load image: " + url);
  8326. if (onError) {
  8327. onError("Error while trying to load image: " + url, err);
  8328. }
  8329. };
  8330. img.addEventListener("load", loadHandler);
  8331. img.addEventListener("error", errorHandler);
  8332. var noIndexedDB = function () {
  8333. img.src = url;
  8334. };
  8335. var loadFromIndexedDB = function () {
  8336. if (database) {
  8337. database.loadImageFromDB(url, img);
  8338. }
  8339. };
  8340. //ANY database to do!
  8341. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8342. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8343. }
  8344. else {
  8345. if (url.indexOf("file:") !== -1) {
  8346. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8347. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8348. try {
  8349. var blobURL;
  8350. try {
  8351. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8352. }
  8353. catch (ex) {
  8354. // Chrome doesn't support oneTimeOnly parameter
  8355. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8356. }
  8357. img.src = blobURL;
  8358. }
  8359. catch (e) {
  8360. img.src = "";
  8361. }
  8362. return img;
  8363. }
  8364. }
  8365. noIndexedDB();
  8366. }
  8367. return img;
  8368. };
  8369. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8370. url = Tools.CleanUrl(url);
  8371. url = Tools.PreprocessUrl(url);
  8372. // If file and file input are set
  8373. if (url.indexOf("file:") !== -1) {
  8374. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8375. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8376. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8377. }
  8378. }
  8379. var loadUrl = Tools.BaseUrl + url;
  8380. var aborted = false;
  8381. var fileRequest = {
  8382. onCompleteObservable: new BABYLON.Observable(),
  8383. abort: function () { return aborted = true; },
  8384. };
  8385. var requestFile = function () {
  8386. var request = new XMLHttpRequest();
  8387. var retryHandle = null;
  8388. fileRequest.abort = function () {
  8389. aborted = true;
  8390. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8391. request.abort();
  8392. }
  8393. if (retryHandle !== null) {
  8394. clearTimeout(retryHandle);
  8395. retryHandle = null;
  8396. }
  8397. };
  8398. var retryLoop = function (retryIndex) {
  8399. request.open('GET', loadUrl, true);
  8400. if (useArrayBuffer) {
  8401. request.responseType = "arraybuffer";
  8402. }
  8403. if (onProgress) {
  8404. request.addEventListener("progress", onProgress);
  8405. }
  8406. var onLoadEnd = function () {
  8407. request.removeEventListener("loadend", onLoadEnd);
  8408. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8409. fileRequest.onCompleteObservable.clear();
  8410. };
  8411. request.addEventListener("loadend", onLoadEnd);
  8412. var onReadyStateChange = function () {
  8413. if (aborted) {
  8414. return;
  8415. }
  8416. // In case of undefined state in some browsers.
  8417. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8418. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8419. request.removeEventListener("readystatechange", onReadyStateChange);
  8420. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8421. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8422. return;
  8423. }
  8424. var retryStrategy = Tools.DefaultRetryStrategy;
  8425. if (retryStrategy) {
  8426. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8427. if (waitTime !== -1) {
  8428. // Prevent the request from completing for retry.
  8429. request.removeEventListener("loadend", onLoadEnd);
  8430. request = new XMLHttpRequest();
  8431. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8432. return;
  8433. }
  8434. }
  8435. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8436. if (onError) {
  8437. onError(request, e);
  8438. }
  8439. else {
  8440. throw e;
  8441. }
  8442. }
  8443. };
  8444. request.addEventListener("readystatechange", onReadyStateChange);
  8445. request.send();
  8446. };
  8447. retryLoop(0);
  8448. };
  8449. // Caching all files
  8450. if (database && database.enableSceneOffline) {
  8451. var noIndexedDB_1 = function () {
  8452. if (!aborted) {
  8453. requestFile();
  8454. }
  8455. };
  8456. var loadFromIndexedDB = function () {
  8457. // TODO: database needs to support aborting and should return a IFileRequest
  8458. if (aborted) {
  8459. return;
  8460. }
  8461. if (database) {
  8462. database.loadFileFromDB(url, function (data) {
  8463. if (!aborted) {
  8464. onSuccess(data);
  8465. }
  8466. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8467. }, onProgress ? function (event) {
  8468. if (!aborted) {
  8469. onProgress(event);
  8470. }
  8471. } : undefined, noIndexedDB_1, useArrayBuffer);
  8472. }
  8473. };
  8474. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8475. }
  8476. else {
  8477. requestFile();
  8478. }
  8479. return fileRequest;
  8480. };
  8481. /**
  8482. * Load a script (identified by an url). When the url returns, the
  8483. * content of this file is added into a new script element, attached to the DOM (body element)
  8484. */
  8485. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8486. var head = document.getElementsByTagName('head')[0];
  8487. var script = document.createElement('script');
  8488. script.type = 'text/javascript';
  8489. script.src = scriptUrl;
  8490. script.onload = function () {
  8491. if (onSuccess) {
  8492. onSuccess();
  8493. }
  8494. };
  8495. script.onerror = function (e) {
  8496. if (onError) {
  8497. onError("Unable to load script", e);
  8498. }
  8499. };
  8500. head.appendChild(script);
  8501. };
  8502. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8503. var reader = new FileReader();
  8504. var request = {
  8505. onCompleteObservable: new BABYLON.Observable(),
  8506. abort: function () { return reader.abort(); },
  8507. };
  8508. reader.onloadend = function (e) {
  8509. request.onCompleteObservable.notifyObservers(request);
  8510. };
  8511. reader.onload = function (e) {
  8512. //target doesn't have result from ts 1.3
  8513. callback(e.target['result']);
  8514. };
  8515. reader.onprogress = progressCallback;
  8516. reader.readAsDataURL(fileToLoad);
  8517. return request;
  8518. };
  8519. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8520. var reader = new FileReader();
  8521. var request = {
  8522. onCompleteObservable: new BABYLON.Observable(),
  8523. abort: function () { return reader.abort(); },
  8524. };
  8525. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8526. reader.onerror = function (e) {
  8527. Tools.Log("Error while reading file: " + fileToLoad.name);
  8528. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8529. };
  8530. reader.onload = function (e) {
  8531. //target doesn't have result from ts 1.3
  8532. callback(e.target['result']);
  8533. };
  8534. if (progressCallBack) {
  8535. reader.onprogress = progressCallBack;
  8536. }
  8537. if (!useArrayBuffer) {
  8538. // Asynchronous read
  8539. reader.readAsText(fileToLoad);
  8540. }
  8541. else {
  8542. reader.readAsArrayBuffer(fileToLoad);
  8543. }
  8544. return request;
  8545. };
  8546. //returns a downloadable url to a file content.
  8547. Tools.FileAsURL = function (content) {
  8548. var fileBlob = new Blob([content]);
  8549. var url = window.URL || window.webkitURL;
  8550. var link = url.createObjectURL(fileBlob);
  8551. return link;
  8552. };
  8553. // Misc.
  8554. Tools.Format = function (value, decimals) {
  8555. if (decimals === void 0) { decimals = 2; }
  8556. return value.toFixed(decimals);
  8557. };
  8558. Tools.CheckExtends = function (v, min, max) {
  8559. if (v.x < min.x)
  8560. min.x = v.x;
  8561. if (v.y < min.y)
  8562. min.y = v.y;
  8563. if (v.z < min.z)
  8564. min.z = v.z;
  8565. if (v.x > max.x)
  8566. max.x = v.x;
  8567. if (v.y > max.y)
  8568. max.y = v.y;
  8569. if (v.z > max.z)
  8570. max.z = v.z;
  8571. };
  8572. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8573. for (var prop in source) {
  8574. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8575. continue;
  8576. }
  8577. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8578. continue;
  8579. }
  8580. var sourceValue = source[prop];
  8581. var typeOfSourceValue = typeof sourceValue;
  8582. if (typeOfSourceValue === "function") {
  8583. continue;
  8584. }
  8585. try {
  8586. if (typeOfSourceValue === "object") {
  8587. if (sourceValue instanceof Array) {
  8588. destination[prop] = [];
  8589. if (sourceValue.length > 0) {
  8590. if (typeof sourceValue[0] == "object") {
  8591. for (var index = 0; index < sourceValue.length; index++) {
  8592. var clonedValue = cloneValue(sourceValue[index], destination);
  8593. if (destination[prop].indexOf(clonedValue) === -1) {
  8594. destination[prop].push(clonedValue);
  8595. }
  8596. }
  8597. }
  8598. else {
  8599. destination[prop] = sourceValue.slice(0);
  8600. }
  8601. }
  8602. }
  8603. else {
  8604. destination[prop] = cloneValue(sourceValue, destination);
  8605. }
  8606. }
  8607. else {
  8608. destination[prop] = sourceValue;
  8609. }
  8610. }
  8611. catch (e) {
  8612. // Just ignore error (it could be because of a read-only property)
  8613. }
  8614. }
  8615. };
  8616. Tools.IsEmpty = function (obj) {
  8617. for (var i in obj) {
  8618. if (obj.hasOwnProperty(i)) {
  8619. return false;
  8620. }
  8621. }
  8622. return true;
  8623. };
  8624. Tools.RegisterTopRootEvents = function (events) {
  8625. for (var index = 0; index < events.length; index++) {
  8626. var event = events[index];
  8627. window.addEventListener(event.name, event.handler, false);
  8628. try {
  8629. if (window.parent) {
  8630. window.parent.addEventListener(event.name, event.handler, false);
  8631. }
  8632. }
  8633. catch (e) {
  8634. // Silently fails...
  8635. }
  8636. }
  8637. };
  8638. Tools.UnregisterTopRootEvents = function (events) {
  8639. for (var index = 0; index < events.length; index++) {
  8640. var event = events[index];
  8641. window.removeEventListener(event.name, event.handler);
  8642. try {
  8643. if (window.parent) {
  8644. window.parent.removeEventListener(event.name, event.handler);
  8645. }
  8646. }
  8647. catch (e) {
  8648. // Silently fails...
  8649. }
  8650. }
  8651. };
  8652. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8653. if (mimeType === void 0) { mimeType = "image/png"; }
  8654. // Read the contents of the framebuffer
  8655. var numberOfChannelsByLine = width * 4;
  8656. var halfHeight = height / 2;
  8657. //Reading datas from WebGL
  8658. var data = engine.readPixels(0, 0, width, height);
  8659. //To flip image on Y axis.
  8660. for (var i = 0; i < halfHeight; i++) {
  8661. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8662. var currentCell = j + i * numberOfChannelsByLine;
  8663. var targetLine = height - i - 1;
  8664. var targetCell = j + targetLine * numberOfChannelsByLine;
  8665. var temp = data[currentCell];
  8666. data[currentCell] = data[targetCell];
  8667. data[targetCell] = temp;
  8668. }
  8669. }
  8670. // Create a 2D canvas to store the result
  8671. if (!screenshotCanvas) {
  8672. screenshotCanvas = document.createElement('canvas');
  8673. }
  8674. screenshotCanvas.width = width;
  8675. screenshotCanvas.height = height;
  8676. var context = screenshotCanvas.getContext('2d');
  8677. if (context) {
  8678. // Copy the pixels to a 2D canvas
  8679. var imageData = context.createImageData(width, height);
  8680. var castData = (imageData.data);
  8681. castData.set(data);
  8682. context.putImageData(imageData, 0, 0);
  8683. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8684. }
  8685. };
  8686. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8687. if (mimeType === void 0) { mimeType = "image/png"; }
  8688. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8689. if (successCallback) {
  8690. successCallback(base64Image);
  8691. }
  8692. else {
  8693. // We need HTMLCanvasElement.toBlob for HD screenshots
  8694. if (!screenshotCanvas.toBlob) {
  8695. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8696. screenshotCanvas.toBlob = function (callback, type, quality) {
  8697. var _this = this;
  8698. setTimeout(function () {
  8699. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8700. for (var i = 0; i < len; i++) {
  8701. arr[i] = binStr.charCodeAt(i);
  8702. }
  8703. callback(new Blob([arr], { type: type || 'image/png' }));
  8704. });
  8705. };
  8706. }
  8707. screenshotCanvas.toBlob(function (blob) {
  8708. var url = URL.createObjectURL(blob);
  8709. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8710. if (("download" in document.createElement("a"))) {
  8711. var a = window.document.createElement("a");
  8712. a.href = url;
  8713. if (fileName) {
  8714. a.setAttribute("download", fileName);
  8715. }
  8716. else {
  8717. var date = new Date();
  8718. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8719. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8720. }
  8721. window.document.body.appendChild(a);
  8722. a.addEventListener("click", function () {
  8723. if (a.parentElement) {
  8724. a.parentElement.removeChild(a);
  8725. }
  8726. });
  8727. a.click();
  8728. }
  8729. else {
  8730. var newWindow = window.open("");
  8731. if (!newWindow)
  8732. return;
  8733. var img = newWindow.document.createElement("img");
  8734. img.onload = function () {
  8735. // no longer need to read the blob so it's revoked
  8736. URL.revokeObjectURL(url);
  8737. };
  8738. img.src = url;
  8739. newWindow.document.body.appendChild(img);
  8740. }
  8741. });
  8742. }
  8743. };
  8744. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8745. if (mimeType === void 0) { mimeType = "image/png"; }
  8746. var width;
  8747. var height;
  8748. // If a precision value is specified
  8749. if (size.precision) {
  8750. width = Math.round(engine.getRenderWidth() * size.precision);
  8751. height = Math.round(width / engine.getAspectRatio(camera));
  8752. }
  8753. else if (size.width && size.height) {
  8754. width = size.width;
  8755. height = size.height;
  8756. }
  8757. else if (size.width && !size.height) {
  8758. width = size.width;
  8759. height = Math.round(width / engine.getAspectRatio(camera));
  8760. }
  8761. else if (size.height && !size.width) {
  8762. height = size.height;
  8763. width = Math.round(height * engine.getAspectRatio(camera));
  8764. }
  8765. else if (!isNaN(size)) {
  8766. height = size;
  8767. width = size;
  8768. }
  8769. else {
  8770. Tools.Error("Invalid 'size' parameter !");
  8771. return;
  8772. }
  8773. if (!screenshotCanvas) {
  8774. screenshotCanvas = document.createElement('canvas');
  8775. }
  8776. screenshotCanvas.width = width;
  8777. screenshotCanvas.height = height;
  8778. var renderContext = screenshotCanvas.getContext("2d");
  8779. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8780. var newWidth = width;
  8781. var newHeight = newWidth / ratio;
  8782. if (newHeight > height) {
  8783. newHeight = height;
  8784. newWidth = newHeight * ratio;
  8785. }
  8786. var offsetX = Math.max(0, width - newWidth) / 2;
  8787. var offsetY = Math.max(0, height - newHeight) / 2;
  8788. var renderingCanvas = engine.getRenderingCanvas();
  8789. if (renderContext && renderingCanvas) {
  8790. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8791. }
  8792. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8793. };
  8794. /**
  8795. * Generates an image screenshot from the specified camera.
  8796. *
  8797. * @param engine The engine to use for rendering
  8798. * @param camera The camera to use for rendering
  8799. * @param size This parameter can be set to a single number or to an object with the
  8800. * following (optional) properties: precision, width, height. If a single number is passed,
  8801. * it will be used for both width and height. If an object is passed, the screenshot size
  8802. * will be derived from the parameters. The precision property is a multiplier allowing
  8803. * rendering at a higher or lower resolution.
  8804. * @param successCallback The callback receives a single parameter which contains the
  8805. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8806. * src parameter of an <img> to display it.
  8807. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8808. * Check your browser for supported MIME types.
  8809. * @param samples Texture samples (default: 1)
  8810. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8811. * @param fileName A name for for the downloaded file.
  8812. * @constructor
  8813. */
  8814. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8815. if (mimeType === void 0) { mimeType = "image/png"; }
  8816. if (samples === void 0) { samples = 1; }
  8817. if (antialiasing === void 0) { antialiasing = false; }
  8818. var width;
  8819. var height;
  8820. //If a precision value is specified
  8821. if (size.precision) {
  8822. width = Math.round(engine.getRenderWidth() * size.precision);
  8823. height = Math.round(width / engine.getAspectRatio(camera));
  8824. size = { width: width, height: height };
  8825. }
  8826. else if (size.width && size.height) {
  8827. width = size.width;
  8828. height = size.height;
  8829. }
  8830. else if (size.width && !size.height) {
  8831. width = size.width;
  8832. height = Math.round(width / engine.getAspectRatio(camera));
  8833. size = { width: width, height: height };
  8834. }
  8835. else if (size.height && !size.width) {
  8836. height = size.height;
  8837. width = Math.round(height * engine.getAspectRatio(camera));
  8838. size = { width: width, height: height };
  8839. }
  8840. else if (!isNaN(size)) {
  8841. height = size;
  8842. width = size;
  8843. }
  8844. else {
  8845. Tools.Error("Invalid 'size' parameter !");
  8846. return;
  8847. }
  8848. var scene = camera.getScene();
  8849. var previousCamera = null;
  8850. if (scene.activeCamera !== camera) {
  8851. previousCamera = scene.activeCamera;
  8852. scene.activeCamera = camera;
  8853. }
  8854. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8855. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8856. texture.renderList = null;
  8857. texture.samples = samples;
  8858. if (antialiasing) {
  8859. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8860. }
  8861. texture.onAfterRenderObservable.add(function () {
  8862. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8863. });
  8864. scene.incrementRenderId();
  8865. scene.resetCachedMaterial();
  8866. texture.render(true);
  8867. texture.dispose();
  8868. if (previousCamera) {
  8869. scene.activeCamera = previousCamera;
  8870. }
  8871. camera.getProjectionMatrix(true); // Force cache refresh;
  8872. };
  8873. // XHR response validator for local file scenario
  8874. Tools.ValidateXHRData = function (xhr, dataType) {
  8875. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8876. if (dataType === void 0) { dataType = 7; }
  8877. try {
  8878. if (dataType & 1) {
  8879. if (xhr.responseText && xhr.responseText.length > 0) {
  8880. return true;
  8881. }
  8882. else if (dataType === 1) {
  8883. return false;
  8884. }
  8885. }
  8886. if (dataType & 2) {
  8887. // Check header width and height since there is no "TGA" magic number
  8888. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8889. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8890. return true;
  8891. }
  8892. else if (dataType === 2) {
  8893. return false;
  8894. }
  8895. }
  8896. if (dataType & 4) {
  8897. // Check for the "DDS" magic number
  8898. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8899. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8900. return true;
  8901. }
  8902. else {
  8903. return false;
  8904. }
  8905. }
  8906. }
  8907. catch (e) {
  8908. // Global protection
  8909. }
  8910. return false;
  8911. };
  8912. /**
  8913. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8914. * Be aware Math.random() could cause collisions, but:
  8915. * "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"
  8916. */
  8917. Tools.RandomId = function () {
  8918. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8919. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8920. return v.toString(16);
  8921. });
  8922. };
  8923. /**
  8924. * Test if the given uri is a base64 string.
  8925. * @param uri The uri to test
  8926. * @return True if the uri is a base64 string or false otherwise.
  8927. */
  8928. Tools.IsBase64 = function (uri) {
  8929. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8930. };
  8931. /**
  8932. * Decode the given base64 uri.
  8933. * @param uri The uri to decode
  8934. * @return The decoded base64 data.
  8935. */
  8936. Tools.DecodeBase64 = function (uri) {
  8937. var decodedString = atob(uri.split(",")[1]);
  8938. var bufferLength = decodedString.length;
  8939. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8940. for (var i = 0; i < bufferLength; i++) {
  8941. bufferView[i] = decodedString.charCodeAt(i);
  8942. }
  8943. return bufferView.buffer;
  8944. };
  8945. Object.defineProperty(Tools, "NoneLogLevel", {
  8946. get: function () {
  8947. return Tools._NoneLogLevel;
  8948. },
  8949. enumerable: true,
  8950. configurable: true
  8951. });
  8952. Object.defineProperty(Tools, "MessageLogLevel", {
  8953. get: function () {
  8954. return Tools._MessageLogLevel;
  8955. },
  8956. enumerable: true,
  8957. configurable: true
  8958. });
  8959. Object.defineProperty(Tools, "WarningLogLevel", {
  8960. get: function () {
  8961. return Tools._WarningLogLevel;
  8962. },
  8963. enumerable: true,
  8964. configurable: true
  8965. });
  8966. Object.defineProperty(Tools, "ErrorLogLevel", {
  8967. get: function () {
  8968. return Tools._ErrorLogLevel;
  8969. },
  8970. enumerable: true,
  8971. configurable: true
  8972. });
  8973. Object.defineProperty(Tools, "AllLogLevel", {
  8974. get: function () {
  8975. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8976. },
  8977. enumerable: true,
  8978. configurable: true
  8979. });
  8980. Tools._AddLogEntry = function (entry) {
  8981. Tools._LogCache = entry + Tools._LogCache;
  8982. if (Tools.OnNewCacheEntry) {
  8983. Tools.OnNewCacheEntry(entry);
  8984. }
  8985. };
  8986. Tools._FormatMessage = function (message) {
  8987. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8988. var date = new Date();
  8989. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8990. };
  8991. Tools._LogDisabled = function (message) {
  8992. // nothing to do
  8993. };
  8994. Tools._LogEnabled = function (message) {
  8995. var formattedMessage = Tools._FormatMessage(message);
  8996. console.log("BJS - " + formattedMessage);
  8997. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8998. Tools._AddLogEntry(entry);
  8999. };
  9000. Tools._WarnDisabled = function (message) {
  9001. // nothing to do
  9002. };
  9003. Tools._WarnEnabled = function (message) {
  9004. var formattedMessage = Tools._FormatMessage(message);
  9005. console.warn("BJS - " + formattedMessage);
  9006. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9007. Tools._AddLogEntry(entry);
  9008. };
  9009. Tools._ErrorDisabled = function (message) {
  9010. // nothing to do
  9011. };
  9012. Tools._ErrorEnabled = function (message) {
  9013. Tools.errorsCount++;
  9014. var formattedMessage = Tools._FormatMessage(message);
  9015. console.error("BJS - " + formattedMessage);
  9016. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9017. Tools._AddLogEntry(entry);
  9018. };
  9019. Object.defineProperty(Tools, "LogCache", {
  9020. get: function () {
  9021. return Tools._LogCache;
  9022. },
  9023. enumerable: true,
  9024. configurable: true
  9025. });
  9026. Tools.ClearLogCache = function () {
  9027. Tools._LogCache = "";
  9028. Tools.errorsCount = 0;
  9029. };
  9030. Object.defineProperty(Tools, "LogLevels", {
  9031. set: function (level) {
  9032. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9033. Tools.Log = Tools._LogEnabled;
  9034. }
  9035. else {
  9036. Tools.Log = Tools._LogDisabled;
  9037. }
  9038. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9039. Tools.Warn = Tools._WarnEnabled;
  9040. }
  9041. else {
  9042. Tools.Warn = Tools._WarnDisabled;
  9043. }
  9044. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9045. Tools.Error = Tools._ErrorEnabled;
  9046. }
  9047. else {
  9048. Tools.Error = Tools._ErrorDisabled;
  9049. }
  9050. },
  9051. enumerable: true,
  9052. configurable: true
  9053. });
  9054. Tools.IsWindowObjectExist = function () {
  9055. return (typeof window) !== "undefined";
  9056. };
  9057. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9058. get: function () {
  9059. return Tools._PerformanceNoneLogLevel;
  9060. },
  9061. enumerable: true,
  9062. configurable: true
  9063. });
  9064. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9065. get: function () {
  9066. return Tools._PerformanceUserMarkLogLevel;
  9067. },
  9068. enumerable: true,
  9069. configurable: true
  9070. });
  9071. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9072. get: function () {
  9073. return Tools._PerformanceConsoleLogLevel;
  9074. },
  9075. enumerable: true,
  9076. configurable: true
  9077. });
  9078. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9079. set: function (level) {
  9080. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9081. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9082. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9083. return;
  9084. }
  9085. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9086. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9087. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9088. return;
  9089. }
  9090. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9091. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9092. },
  9093. enumerable: true,
  9094. configurable: true
  9095. });
  9096. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9097. };
  9098. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9099. };
  9100. Tools._StartUserMark = function (counterName, condition) {
  9101. if (condition === void 0) { condition = true; }
  9102. if (!Tools._performance) {
  9103. if (!Tools.IsWindowObjectExist()) {
  9104. return;
  9105. }
  9106. Tools._performance = window.performance;
  9107. }
  9108. if (!condition || !Tools._performance.mark) {
  9109. return;
  9110. }
  9111. Tools._performance.mark(counterName + "-Begin");
  9112. };
  9113. Tools._EndUserMark = function (counterName, condition) {
  9114. if (condition === void 0) { condition = true; }
  9115. if (!condition || !Tools._performance.mark) {
  9116. return;
  9117. }
  9118. Tools._performance.mark(counterName + "-End");
  9119. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9120. };
  9121. Tools._StartPerformanceConsole = function (counterName, condition) {
  9122. if (condition === void 0) { condition = true; }
  9123. if (!condition) {
  9124. return;
  9125. }
  9126. Tools._StartUserMark(counterName, condition);
  9127. if (console.time) {
  9128. console.time(counterName);
  9129. }
  9130. };
  9131. Tools._EndPerformanceConsole = function (counterName, condition) {
  9132. if (condition === void 0) { condition = true; }
  9133. if (!condition) {
  9134. return;
  9135. }
  9136. Tools._EndUserMark(counterName, condition);
  9137. if (console.time) {
  9138. console.timeEnd(counterName);
  9139. }
  9140. };
  9141. Object.defineProperty(Tools, "Now", {
  9142. get: function () {
  9143. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9144. return window.performance.now();
  9145. }
  9146. return new Date().getTime();
  9147. },
  9148. enumerable: true,
  9149. configurable: true
  9150. });
  9151. /**
  9152. * This method will return the name of the class used to create the instance of the given object.
  9153. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9154. * @param object the object to get the class name from
  9155. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9156. */
  9157. Tools.GetClassName = function (object, isType) {
  9158. if (isType === void 0) { isType = false; }
  9159. var name = null;
  9160. if (!isType && object.getClassName) {
  9161. name = object.getClassName();
  9162. }
  9163. else {
  9164. if (object instanceof Object) {
  9165. var classObj = isType ? object : Object.getPrototypeOf(object);
  9166. name = classObj.constructor["__bjsclassName__"];
  9167. }
  9168. if (!name) {
  9169. name = typeof object;
  9170. }
  9171. }
  9172. return name;
  9173. };
  9174. Tools.First = function (array, predicate) {
  9175. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9176. var el = array_1[_i];
  9177. if (predicate(el)) {
  9178. return el;
  9179. }
  9180. }
  9181. return null;
  9182. };
  9183. /**
  9184. * This method will return the name of the full name of the class, including its owning module (if any).
  9185. * 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).
  9186. * @param object the object to get the class name from
  9187. * @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.
  9188. */
  9189. Tools.getFullClassName = function (object, isType) {
  9190. if (isType === void 0) { isType = false; }
  9191. var className = null;
  9192. var moduleName = null;
  9193. if (!isType && object.getClassName) {
  9194. className = object.getClassName();
  9195. }
  9196. else {
  9197. if (object instanceof Object) {
  9198. var classObj = isType ? object : Object.getPrototypeOf(object);
  9199. className = classObj.constructor["__bjsclassName__"];
  9200. moduleName = classObj.constructor["__bjsmoduleName__"];
  9201. }
  9202. if (!className) {
  9203. className = typeof object;
  9204. }
  9205. }
  9206. if (!className) {
  9207. return null;
  9208. }
  9209. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9210. };
  9211. /**
  9212. * 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.
  9213. * @param array
  9214. */
  9215. Tools.arrayOrStringFeeder = function (array) {
  9216. return function (index) {
  9217. if (index >= array.length) {
  9218. return null;
  9219. }
  9220. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9221. if (val && val.getHashCode) {
  9222. val = val.getHashCode();
  9223. }
  9224. if (typeof val === "string") {
  9225. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9226. }
  9227. return val;
  9228. };
  9229. };
  9230. /**
  9231. * Compute the hashCode of a stream of number
  9232. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9233. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9234. * @return the hash code computed
  9235. */
  9236. Tools.hashCodeFromStream = function (feeder) {
  9237. // Based from here: http://stackoverflow.com/a/7616484/802124
  9238. var hash = 0;
  9239. var index = 0;
  9240. var chr = feeder(index++);
  9241. while (chr != null) {
  9242. hash = ((hash << 5) - hash) + chr;
  9243. hash |= 0; // Convert to 32bit integer
  9244. chr = feeder(index++);
  9245. }
  9246. return hash;
  9247. };
  9248. /**
  9249. * Returns a promise that resolves after the given amount of time.
  9250. * @param delay Number of milliseconds to delay
  9251. * @returns Promise that resolves after the given amount of time
  9252. */
  9253. Tools.DelayAsync = function (delay) {
  9254. return new Promise(function (resolve) {
  9255. setTimeout(function () {
  9256. resolve();
  9257. }, delay);
  9258. });
  9259. };
  9260. Tools.BaseUrl = "";
  9261. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9262. /**
  9263. * Default behaviour for cors in the application.
  9264. * It can be a string if the expected behavior is identical in the entire app.
  9265. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9266. */
  9267. Tools.CorsBehavior = "anonymous";
  9268. Tools.UseFallbackTexture = true;
  9269. /**
  9270. * Use this object to register external classes like custom textures or material
  9271. * to allow the laoders to instantiate them
  9272. */
  9273. Tools.RegisteredExternalClasses = {};
  9274. // Used in case of a texture loading problem
  9275. 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";
  9276. Tools.PreprocessUrl = function (url) {
  9277. return url;
  9278. };
  9279. // Logs
  9280. Tools._NoneLogLevel = 0;
  9281. Tools._MessageLogLevel = 1;
  9282. Tools._WarningLogLevel = 2;
  9283. Tools._ErrorLogLevel = 4;
  9284. Tools._LogCache = "";
  9285. Tools.errorsCount = 0;
  9286. Tools.Log = Tools._LogEnabled;
  9287. Tools.Warn = Tools._WarnEnabled;
  9288. Tools.Error = Tools._ErrorEnabled;
  9289. // Performances
  9290. Tools._PerformanceNoneLogLevel = 0;
  9291. Tools._PerformanceUserMarkLogLevel = 1;
  9292. Tools._PerformanceConsoleLogLevel = 2;
  9293. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9294. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9295. return Tools;
  9296. }());
  9297. BABYLON.Tools = Tools;
  9298. /**
  9299. * This class is used to track a performance counter which is number based.
  9300. * The user has access to many properties which give statistics of different nature
  9301. *
  9302. * The implementer can track two kinds of Performance Counter: time and count
  9303. * 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.
  9304. * 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.
  9305. */
  9306. var PerfCounter = /** @class */ (function () {
  9307. function PerfCounter() {
  9308. this._startMonitoringTime = 0;
  9309. this._min = 0;
  9310. this._max = 0;
  9311. this._average = 0;
  9312. this._lastSecAverage = 0;
  9313. this._current = 0;
  9314. this._totalValueCount = 0;
  9315. this._totalAccumulated = 0;
  9316. this._lastSecAccumulated = 0;
  9317. this._lastSecTime = 0;
  9318. this._lastSecValueCount = 0;
  9319. }
  9320. Object.defineProperty(PerfCounter.prototype, "min", {
  9321. /**
  9322. * Returns the smallest value ever
  9323. */
  9324. get: function () {
  9325. return this._min;
  9326. },
  9327. enumerable: true,
  9328. configurable: true
  9329. });
  9330. Object.defineProperty(PerfCounter.prototype, "max", {
  9331. /**
  9332. * Returns the biggest value ever
  9333. */
  9334. get: function () {
  9335. return this._max;
  9336. },
  9337. enumerable: true,
  9338. configurable: true
  9339. });
  9340. Object.defineProperty(PerfCounter.prototype, "average", {
  9341. /**
  9342. * Returns the average value since the performance counter is running
  9343. */
  9344. get: function () {
  9345. return this._average;
  9346. },
  9347. enumerable: true,
  9348. configurable: true
  9349. });
  9350. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9351. /**
  9352. * Returns the average value of the last second the counter was monitored
  9353. */
  9354. get: function () {
  9355. return this._lastSecAverage;
  9356. },
  9357. enumerable: true,
  9358. configurable: true
  9359. });
  9360. Object.defineProperty(PerfCounter.prototype, "current", {
  9361. /**
  9362. * Returns the current value
  9363. */
  9364. get: function () {
  9365. return this._current;
  9366. },
  9367. enumerable: true,
  9368. configurable: true
  9369. });
  9370. Object.defineProperty(PerfCounter.prototype, "total", {
  9371. get: function () {
  9372. return this._totalAccumulated;
  9373. },
  9374. enumerable: true,
  9375. configurable: true
  9376. });
  9377. Object.defineProperty(PerfCounter.prototype, "count", {
  9378. get: function () {
  9379. return this._totalValueCount;
  9380. },
  9381. enumerable: true,
  9382. configurable: true
  9383. });
  9384. /**
  9385. * Call this method to start monitoring a new frame.
  9386. * 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.
  9387. */
  9388. PerfCounter.prototype.fetchNewFrame = function () {
  9389. this._totalValueCount++;
  9390. this._current = 0;
  9391. this._lastSecValueCount++;
  9392. };
  9393. /**
  9394. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9395. * @param newCount the count value to add to the monitored count
  9396. * @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.
  9397. */
  9398. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9399. if (!PerfCounter.Enabled) {
  9400. return;
  9401. }
  9402. this._current += newCount;
  9403. if (fetchResult) {
  9404. this._fetchResult();
  9405. }
  9406. };
  9407. /**
  9408. * Start monitoring this performance counter
  9409. */
  9410. PerfCounter.prototype.beginMonitoring = function () {
  9411. if (!PerfCounter.Enabled) {
  9412. return;
  9413. }
  9414. this._startMonitoringTime = Tools.Now;
  9415. };
  9416. /**
  9417. * Compute the time lapsed since the previous beginMonitoring() call.
  9418. * @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
  9419. */
  9420. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9421. if (newFrame === void 0) { newFrame = true; }
  9422. if (!PerfCounter.Enabled) {
  9423. return;
  9424. }
  9425. if (newFrame) {
  9426. this.fetchNewFrame();
  9427. }
  9428. var currentTime = Tools.Now;
  9429. this._current = currentTime - this._startMonitoringTime;
  9430. if (newFrame) {
  9431. this._fetchResult();
  9432. }
  9433. };
  9434. PerfCounter.prototype._fetchResult = function () {
  9435. this._totalAccumulated += this._current;
  9436. this._lastSecAccumulated += this._current;
  9437. // Min/Max update
  9438. this._min = Math.min(this._min, this._current);
  9439. this._max = Math.max(this._max, this._current);
  9440. this._average = this._totalAccumulated / this._totalValueCount;
  9441. // Reset last sec?
  9442. var now = Tools.Now;
  9443. if ((now - this._lastSecTime) > 1000) {
  9444. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9445. this._lastSecTime = now;
  9446. this._lastSecAccumulated = 0;
  9447. this._lastSecValueCount = 0;
  9448. }
  9449. };
  9450. PerfCounter.Enabled = true;
  9451. return PerfCounter;
  9452. }());
  9453. BABYLON.PerfCounter = PerfCounter;
  9454. /**
  9455. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9456. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9457. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9458. * @param name The name of the class, case should be preserved
  9459. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9460. */
  9461. function className(name, module) {
  9462. return function (target) {
  9463. target["__bjsclassName__"] = name;
  9464. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9465. };
  9466. }
  9467. BABYLON.className = className;
  9468. /**
  9469. * An implementation of a loop for asynchronous functions.
  9470. */
  9471. var AsyncLoop = /** @class */ (function () {
  9472. /**
  9473. * Constroctor.
  9474. * @param iterations the number of iterations.
  9475. * @param _fn the function to run each iteration
  9476. * @param _successCallback the callback that will be called upon succesful execution
  9477. * @param offset starting offset.
  9478. */
  9479. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9480. if (offset === void 0) { offset = 0; }
  9481. this.iterations = iterations;
  9482. this._fn = _fn;
  9483. this._successCallback = _successCallback;
  9484. this.index = offset - 1;
  9485. this._done = false;
  9486. }
  9487. /**
  9488. * Execute the next iteration. Must be called after the last iteration was finished.
  9489. */
  9490. AsyncLoop.prototype.executeNext = function () {
  9491. if (!this._done) {
  9492. if (this.index + 1 < this.iterations) {
  9493. ++this.index;
  9494. this._fn(this);
  9495. }
  9496. else {
  9497. this.breakLoop();
  9498. }
  9499. }
  9500. };
  9501. /**
  9502. * Break the loop and run the success callback.
  9503. */
  9504. AsyncLoop.prototype.breakLoop = function () {
  9505. this._done = true;
  9506. this._successCallback();
  9507. };
  9508. /**
  9509. * Helper function
  9510. */
  9511. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9512. if (offset === void 0) { offset = 0; }
  9513. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9514. loop.executeNext();
  9515. return loop;
  9516. };
  9517. /**
  9518. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9519. * @param iterations total number of iterations
  9520. * @param syncedIterations number of synchronous iterations in each async iteration.
  9521. * @param fn the function to call each iteration.
  9522. * @param callback a success call back that will be called when iterating stops.
  9523. * @param breakFunction a break condition (optional)
  9524. * @param timeout timeout settings for the setTimeout function. default - 0.
  9525. * @constructor
  9526. */
  9527. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9528. if (timeout === void 0) { timeout = 0; }
  9529. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9530. if (breakFunction && breakFunction())
  9531. loop.breakLoop();
  9532. else {
  9533. setTimeout(function () {
  9534. for (var i = 0; i < syncedIterations; ++i) {
  9535. var iteration = (loop.index * syncedIterations) + i;
  9536. if (iteration >= iterations)
  9537. break;
  9538. fn(iteration);
  9539. if (breakFunction && breakFunction()) {
  9540. loop.breakLoop();
  9541. break;
  9542. }
  9543. }
  9544. loop.executeNext();
  9545. }, timeout);
  9546. }
  9547. }, callback);
  9548. };
  9549. return AsyncLoop;
  9550. }());
  9551. BABYLON.AsyncLoop = AsyncLoop;
  9552. })(BABYLON || (BABYLON = {}));
  9553. //# sourceMappingURL=babylon.tools.js.map
  9554. "use strict";
  9555. var BABYLON;
  9556. (function (BABYLON) {
  9557. var PromiseStates;
  9558. (function (PromiseStates) {
  9559. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9560. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9561. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9562. })(PromiseStates || (PromiseStates = {}));
  9563. var FulFillmentAgregator = /** @class */ (function () {
  9564. function FulFillmentAgregator() {
  9565. this.count = 0;
  9566. this.target = 0;
  9567. this.results = [];
  9568. }
  9569. return FulFillmentAgregator;
  9570. }());
  9571. var InternalPromise = /** @class */ (function () {
  9572. function InternalPromise(resolver) {
  9573. var _this = this;
  9574. this._state = PromiseStates.Pending;
  9575. this._children = new Array();
  9576. this._rejectWasConsumed = false;
  9577. if (!resolver) {
  9578. return;
  9579. }
  9580. try {
  9581. resolver(function (value) {
  9582. _this._resolve(value);
  9583. }, function (reason) {
  9584. _this._reject(reason);
  9585. });
  9586. }
  9587. catch (e) {
  9588. this._reject(e);
  9589. }
  9590. }
  9591. InternalPromise.prototype.catch = function (onRejected) {
  9592. return this.then(undefined, onRejected);
  9593. };
  9594. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9595. var _this = this;
  9596. var newPromise = new InternalPromise();
  9597. newPromise._onFulfilled = onFulfilled;
  9598. newPromise._onRejected = onRejected;
  9599. // Composition
  9600. this._children.push(newPromise);
  9601. if (this._state !== PromiseStates.Pending) {
  9602. BABYLON.Tools.SetImmediate(function () {
  9603. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9604. var returnedValue = newPromise._resolve(_this._result);
  9605. if (returnedValue !== undefined && returnedValue !== null) {
  9606. if (returnedValue._state !== undefined) {
  9607. var returnedPromise = returnedValue;
  9608. newPromise._children.push(returnedPromise);
  9609. newPromise = returnedPromise;
  9610. }
  9611. else {
  9612. newPromise._result = returnedValue;
  9613. }
  9614. }
  9615. }
  9616. else {
  9617. newPromise._reject(_this._reason);
  9618. }
  9619. });
  9620. }
  9621. return newPromise;
  9622. };
  9623. InternalPromise.prototype._moveChildren = function (children) {
  9624. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9625. if (this._state === PromiseStates.Fulfilled) {
  9626. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9627. var child = _b[_i];
  9628. child._resolve(this._result);
  9629. }
  9630. }
  9631. else if (this._state === PromiseStates.Rejected) {
  9632. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9633. var child = _d[_c];
  9634. child._reject(this._reason);
  9635. }
  9636. }
  9637. var _a;
  9638. };
  9639. InternalPromise.prototype._resolve = function (value) {
  9640. try {
  9641. this._state = PromiseStates.Fulfilled;
  9642. var returnedValue = null;
  9643. if (this._onFulfilled) {
  9644. returnedValue = this._onFulfilled(value);
  9645. }
  9646. if (returnedValue !== undefined && returnedValue !== null) {
  9647. if (returnedValue._state !== undefined) {
  9648. // Transmit children
  9649. var returnedPromise = returnedValue;
  9650. returnedPromise._moveChildren(this._children);
  9651. value = returnedPromise._result;
  9652. }
  9653. else {
  9654. value = returnedValue;
  9655. }
  9656. }
  9657. this._result = value;
  9658. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9659. var child = _a[_i];
  9660. child._resolve(value);
  9661. }
  9662. this._children.length = 0;
  9663. delete this._onFulfilled;
  9664. delete this._onRejected;
  9665. }
  9666. catch (e) {
  9667. this._reject(e, true);
  9668. }
  9669. };
  9670. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9671. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9672. this._state = PromiseStates.Rejected;
  9673. this._reason = reason;
  9674. if (this._onRejected && !onLocalThrow) {
  9675. try {
  9676. this._onRejected(reason);
  9677. this._rejectWasConsumed = true;
  9678. }
  9679. catch (e) {
  9680. reason = e;
  9681. }
  9682. }
  9683. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9684. var child = _a[_i];
  9685. if (this._rejectWasConsumed) {
  9686. child._resolve(null);
  9687. }
  9688. else {
  9689. child._reject(reason);
  9690. }
  9691. }
  9692. this._children.length = 0;
  9693. delete this._onFulfilled;
  9694. delete this._onRejected;
  9695. };
  9696. InternalPromise.resolve = function (value) {
  9697. var newPromise = new InternalPromise();
  9698. newPromise._resolve(value);
  9699. return newPromise;
  9700. };
  9701. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9702. promise.then(function (value) {
  9703. agregator.results[index] = value;
  9704. agregator.count++;
  9705. if (agregator.count === agregator.target) {
  9706. agregator.rootPromise._resolve(agregator.results);
  9707. }
  9708. return null;
  9709. }, function (reason) {
  9710. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9711. agregator.rootPromise._reject(reason);
  9712. }
  9713. });
  9714. };
  9715. InternalPromise.all = function (promises) {
  9716. var newPromise = new InternalPromise();
  9717. var agregator = new FulFillmentAgregator();
  9718. agregator.target = promises.length;
  9719. agregator.rootPromise = newPromise;
  9720. if (promises.length) {
  9721. for (var index = 0; index < promises.length; index++) {
  9722. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9723. }
  9724. }
  9725. else {
  9726. newPromise._resolve([]);
  9727. }
  9728. return newPromise;
  9729. };
  9730. InternalPromise.race = function (promises) {
  9731. var newPromise = new InternalPromise();
  9732. if (promises.length) {
  9733. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9734. var promise = promises_1[_i];
  9735. promise.then(function (value) {
  9736. if (newPromise) {
  9737. newPromise._resolve(value);
  9738. newPromise = null;
  9739. }
  9740. return null;
  9741. }, function (reason) {
  9742. if (newPromise) {
  9743. newPromise._reject(reason);
  9744. newPromise = null;
  9745. }
  9746. });
  9747. }
  9748. }
  9749. return newPromise;
  9750. };
  9751. return InternalPromise;
  9752. }());
  9753. /**
  9754. * Helper class that provides a small promise polyfill
  9755. */
  9756. var PromisePolyfill = /** @class */ (function () {
  9757. function PromisePolyfill() {
  9758. }
  9759. /**
  9760. * Static function used to check if the polyfill is required
  9761. * If this is the case then the function will inject the polyfill to window.Promise
  9762. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9763. */
  9764. PromisePolyfill.Apply = function (force) {
  9765. if (force === void 0) { force = false; }
  9766. if (force || typeof Promise === 'undefined') {
  9767. var root = window;
  9768. root.Promise = InternalPromise;
  9769. }
  9770. };
  9771. return PromisePolyfill;
  9772. }());
  9773. BABYLON.PromisePolyfill = PromisePolyfill;
  9774. })(BABYLON || (BABYLON = {}));
  9775. //# sourceMappingURL=babylon.promise.js.map
  9776. "use strict";
  9777. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9778. var BABYLON;
  9779. (function (BABYLON) {
  9780. /**
  9781. * Helper class to push actions to a pool of workers.
  9782. */
  9783. var WorkerPool = /** @class */ (function () {
  9784. /**
  9785. * Constructor
  9786. * @param workers Array of workers to use for actions
  9787. */
  9788. function WorkerPool(workers) {
  9789. this._pendingActions = new Array();
  9790. this._workerInfos = workers.map(function (worker) { return ({
  9791. worker: worker,
  9792. active: false
  9793. }); });
  9794. }
  9795. /**
  9796. * Terminates all workers and clears any pending actions.
  9797. */
  9798. WorkerPool.prototype.dispose = function () {
  9799. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9800. var workerInfo = _a[_i];
  9801. workerInfo.worker.terminate();
  9802. }
  9803. delete this._workerInfos;
  9804. delete this._pendingActions;
  9805. };
  9806. /**
  9807. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9808. * pended until a worker has completed its action.
  9809. * @param action The action to perform. Call onComplete when the action is complete.
  9810. */
  9811. WorkerPool.prototype.push = function (action) {
  9812. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9813. var workerInfo = _a[_i];
  9814. if (!workerInfo.active) {
  9815. this._execute(workerInfo, action);
  9816. return;
  9817. }
  9818. }
  9819. this._pendingActions.push(action);
  9820. };
  9821. WorkerPool.prototype._execute = function (workerInfo, action) {
  9822. var _this = this;
  9823. workerInfo.active = true;
  9824. action(workerInfo.worker, function () {
  9825. workerInfo.active = false;
  9826. var nextAction = _this._pendingActions.shift();
  9827. if (nextAction) {
  9828. _this._execute(workerInfo, nextAction);
  9829. }
  9830. });
  9831. };
  9832. return WorkerPool;
  9833. }());
  9834. BABYLON.WorkerPool = WorkerPool;
  9835. })(BABYLON || (BABYLON = {}));
  9836. //# sourceMappingURL=babylon.workerPool.js.map
  9837. "use strict";
  9838. var BABYLON;
  9839. (function (BABYLON) {
  9840. var _AlphaState = /** @class */ (function () {
  9841. /**
  9842. * Initializes the state.
  9843. */
  9844. function _AlphaState() {
  9845. this._isAlphaBlendDirty = false;
  9846. this._isBlendFunctionParametersDirty = false;
  9847. this._isBlendEquationParametersDirty = false;
  9848. this._isBlendConstantsDirty = false;
  9849. this._alphaBlend = false;
  9850. this._blendFunctionParameters = new Array(4);
  9851. this._blendEquationParameters = new Array(2);
  9852. this._blendConstants = new Array(4);
  9853. this.reset();
  9854. }
  9855. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9856. get: function () {
  9857. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9863. get: function () {
  9864. return this._alphaBlend;
  9865. },
  9866. set: function (value) {
  9867. if (this._alphaBlend === value) {
  9868. return;
  9869. }
  9870. this._alphaBlend = value;
  9871. this._isAlphaBlendDirty = true;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9877. if (this._blendConstants[0] === r &&
  9878. this._blendConstants[1] === g &&
  9879. this._blendConstants[2] === b &&
  9880. this._blendConstants[3] === a) {
  9881. return;
  9882. }
  9883. this._blendConstants[0] = r;
  9884. this._blendConstants[1] = g;
  9885. this._blendConstants[2] = b;
  9886. this._blendConstants[3] = a;
  9887. this._isBlendConstantsDirty = true;
  9888. };
  9889. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9890. if (this._blendFunctionParameters[0] === value0 &&
  9891. this._blendFunctionParameters[1] === value1 &&
  9892. this._blendFunctionParameters[2] === value2 &&
  9893. this._blendFunctionParameters[3] === value3) {
  9894. return;
  9895. }
  9896. this._blendFunctionParameters[0] = value0;
  9897. this._blendFunctionParameters[1] = value1;
  9898. this._blendFunctionParameters[2] = value2;
  9899. this._blendFunctionParameters[3] = value3;
  9900. this._isBlendFunctionParametersDirty = true;
  9901. };
  9902. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9903. if (this._blendEquationParameters[0] === rgb &&
  9904. this._blendEquationParameters[1] === alpha) {
  9905. return;
  9906. }
  9907. this._blendEquationParameters[0] = rgb;
  9908. this._blendEquationParameters[1] = alpha;
  9909. this._isBlendEquationParametersDirty = true;
  9910. };
  9911. _AlphaState.prototype.reset = function () {
  9912. this._alphaBlend = false;
  9913. this._blendFunctionParameters[0] = null;
  9914. this._blendFunctionParameters[1] = null;
  9915. this._blendFunctionParameters[2] = null;
  9916. this._blendFunctionParameters[3] = null;
  9917. this._blendEquationParameters[0] = null;
  9918. this._blendEquationParameters[1] = null;
  9919. this._blendConstants[0] = null;
  9920. this._blendConstants[1] = null;
  9921. this._blendConstants[2] = null;
  9922. this._blendConstants[3] = null;
  9923. this._isAlphaBlendDirty = true;
  9924. this._isBlendFunctionParametersDirty = false;
  9925. this._isBlendEquationParametersDirty = false;
  9926. this._isBlendConstantsDirty = false;
  9927. };
  9928. _AlphaState.prototype.apply = function (gl) {
  9929. if (!this.isDirty) {
  9930. return;
  9931. }
  9932. // Alpha blend
  9933. if (this._isAlphaBlendDirty) {
  9934. if (this._alphaBlend) {
  9935. gl.enable(gl.BLEND);
  9936. }
  9937. else {
  9938. gl.disable(gl.BLEND);
  9939. }
  9940. this._isAlphaBlendDirty = false;
  9941. }
  9942. // Alpha function
  9943. if (this._isBlendFunctionParametersDirty) {
  9944. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9945. this._isBlendFunctionParametersDirty = false;
  9946. }
  9947. // Alpha equation
  9948. if (this._isBlendEquationParametersDirty) {
  9949. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9950. this._isBlendEquationParametersDirty = false;
  9951. }
  9952. // Constants
  9953. if (this._isBlendConstantsDirty) {
  9954. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9955. this._isBlendConstantsDirty = false;
  9956. }
  9957. };
  9958. return _AlphaState;
  9959. }());
  9960. BABYLON._AlphaState = _AlphaState;
  9961. })(BABYLON || (BABYLON = {}));
  9962. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9963. "use strict";
  9964. var BABYLON;
  9965. (function (BABYLON) {
  9966. var _DepthCullingState = /** @class */ (function () {
  9967. /**
  9968. * Initializes the state.
  9969. */
  9970. function _DepthCullingState() {
  9971. this._isDepthTestDirty = false;
  9972. this._isDepthMaskDirty = false;
  9973. this._isDepthFuncDirty = false;
  9974. this._isCullFaceDirty = false;
  9975. this._isCullDirty = false;
  9976. this._isZOffsetDirty = false;
  9977. this._isFrontFaceDirty = false;
  9978. this.reset();
  9979. }
  9980. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9981. get: function () {
  9982. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9983. },
  9984. enumerable: true,
  9985. configurable: true
  9986. });
  9987. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9988. get: function () {
  9989. return this._zOffset;
  9990. },
  9991. set: function (value) {
  9992. if (this._zOffset === value) {
  9993. return;
  9994. }
  9995. this._zOffset = value;
  9996. this._isZOffsetDirty = true;
  9997. },
  9998. enumerable: true,
  9999. configurable: true
  10000. });
  10001. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10002. get: function () {
  10003. return this._cullFace;
  10004. },
  10005. set: function (value) {
  10006. if (this._cullFace === value) {
  10007. return;
  10008. }
  10009. this._cullFace = value;
  10010. this._isCullFaceDirty = true;
  10011. },
  10012. enumerable: true,
  10013. configurable: true
  10014. });
  10015. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10016. get: function () {
  10017. return this._cull;
  10018. },
  10019. set: function (value) {
  10020. if (this._cull === value) {
  10021. return;
  10022. }
  10023. this._cull = value;
  10024. this._isCullDirty = true;
  10025. },
  10026. enumerable: true,
  10027. configurable: true
  10028. });
  10029. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10030. get: function () {
  10031. return this._depthFunc;
  10032. },
  10033. set: function (value) {
  10034. if (this._depthFunc === value) {
  10035. return;
  10036. }
  10037. this._depthFunc = value;
  10038. this._isDepthFuncDirty = true;
  10039. },
  10040. enumerable: true,
  10041. configurable: true
  10042. });
  10043. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10044. get: function () {
  10045. return this._depthMask;
  10046. },
  10047. set: function (value) {
  10048. if (this._depthMask === value) {
  10049. return;
  10050. }
  10051. this._depthMask = value;
  10052. this._isDepthMaskDirty = true;
  10053. },
  10054. enumerable: true,
  10055. configurable: true
  10056. });
  10057. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10058. get: function () {
  10059. return this._depthTest;
  10060. },
  10061. set: function (value) {
  10062. if (this._depthTest === value) {
  10063. return;
  10064. }
  10065. this._depthTest = value;
  10066. this._isDepthTestDirty = true;
  10067. },
  10068. enumerable: true,
  10069. configurable: true
  10070. });
  10071. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10072. get: function () {
  10073. return this._frontFace;
  10074. },
  10075. set: function (value) {
  10076. if (this._frontFace === value) {
  10077. return;
  10078. }
  10079. this._frontFace = value;
  10080. this._isFrontFaceDirty = true;
  10081. },
  10082. enumerable: true,
  10083. configurable: true
  10084. });
  10085. _DepthCullingState.prototype.reset = function () {
  10086. this._depthMask = true;
  10087. this._depthTest = true;
  10088. this._depthFunc = null;
  10089. this._cullFace = null;
  10090. this._cull = null;
  10091. this._zOffset = 0;
  10092. this._frontFace = null;
  10093. this._isDepthTestDirty = true;
  10094. this._isDepthMaskDirty = true;
  10095. this._isDepthFuncDirty = false;
  10096. this._isCullFaceDirty = false;
  10097. this._isCullDirty = false;
  10098. this._isZOffsetDirty = false;
  10099. this._isFrontFaceDirty = false;
  10100. };
  10101. _DepthCullingState.prototype.apply = function (gl) {
  10102. if (!this.isDirty) {
  10103. return;
  10104. }
  10105. // Cull
  10106. if (this._isCullDirty) {
  10107. if (this.cull) {
  10108. gl.enable(gl.CULL_FACE);
  10109. }
  10110. else {
  10111. gl.disable(gl.CULL_FACE);
  10112. }
  10113. this._isCullDirty = false;
  10114. }
  10115. // Cull face
  10116. if (this._isCullFaceDirty) {
  10117. gl.cullFace(this.cullFace);
  10118. this._isCullFaceDirty = false;
  10119. }
  10120. // Depth mask
  10121. if (this._isDepthMaskDirty) {
  10122. gl.depthMask(this.depthMask);
  10123. this._isDepthMaskDirty = false;
  10124. }
  10125. // Depth test
  10126. if (this._isDepthTestDirty) {
  10127. if (this.depthTest) {
  10128. gl.enable(gl.DEPTH_TEST);
  10129. }
  10130. else {
  10131. gl.disable(gl.DEPTH_TEST);
  10132. }
  10133. this._isDepthTestDirty = false;
  10134. }
  10135. // Depth func
  10136. if (this._isDepthFuncDirty) {
  10137. gl.depthFunc(this.depthFunc);
  10138. this._isDepthFuncDirty = false;
  10139. }
  10140. // zOffset
  10141. if (this._isZOffsetDirty) {
  10142. if (this.zOffset) {
  10143. gl.enable(gl.POLYGON_OFFSET_FILL);
  10144. gl.polygonOffset(this.zOffset, 0);
  10145. }
  10146. else {
  10147. gl.disable(gl.POLYGON_OFFSET_FILL);
  10148. }
  10149. this._isZOffsetDirty = false;
  10150. }
  10151. // Front face
  10152. if (this._isFrontFaceDirty) {
  10153. gl.frontFace(this.frontFace);
  10154. this._isFrontFaceDirty = false;
  10155. }
  10156. };
  10157. return _DepthCullingState;
  10158. }());
  10159. BABYLON._DepthCullingState = _DepthCullingState;
  10160. })(BABYLON || (BABYLON = {}));
  10161. //# sourceMappingURL=babylon.depthCullingState.js.map
  10162. "use strict";
  10163. var BABYLON;
  10164. (function (BABYLON) {
  10165. var _StencilState = /** @class */ (function () {
  10166. function _StencilState() {
  10167. this._isStencilTestDirty = false;
  10168. this._isStencilMaskDirty = false;
  10169. this._isStencilFuncDirty = false;
  10170. this._isStencilOpDirty = false;
  10171. this.reset();
  10172. }
  10173. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10174. get: function () {
  10175. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10176. },
  10177. enumerable: true,
  10178. configurable: true
  10179. });
  10180. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10181. get: function () {
  10182. return this._stencilFunc;
  10183. },
  10184. set: function (value) {
  10185. if (this._stencilFunc === value) {
  10186. return;
  10187. }
  10188. this._stencilFunc = value;
  10189. this._isStencilFuncDirty = true;
  10190. },
  10191. enumerable: true,
  10192. configurable: true
  10193. });
  10194. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10195. get: function () {
  10196. return this._stencilFuncRef;
  10197. },
  10198. set: function (value) {
  10199. if (this._stencilFuncRef === value) {
  10200. return;
  10201. }
  10202. this._stencilFuncRef = value;
  10203. this._isStencilFuncDirty = true;
  10204. },
  10205. enumerable: true,
  10206. configurable: true
  10207. });
  10208. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10209. get: function () {
  10210. return this._stencilFuncMask;
  10211. },
  10212. set: function (value) {
  10213. if (this._stencilFuncMask === value) {
  10214. return;
  10215. }
  10216. this._stencilFuncMask = value;
  10217. this._isStencilFuncDirty = true;
  10218. },
  10219. enumerable: true,
  10220. configurable: true
  10221. });
  10222. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10223. get: function () {
  10224. return this._stencilOpStencilFail;
  10225. },
  10226. set: function (value) {
  10227. if (this._stencilOpStencilFail === value) {
  10228. return;
  10229. }
  10230. this._stencilOpStencilFail = value;
  10231. this._isStencilOpDirty = true;
  10232. },
  10233. enumerable: true,
  10234. configurable: true
  10235. });
  10236. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10237. get: function () {
  10238. return this._stencilOpDepthFail;
  10239. },
  10240. set: function (value) {
  10241. if (this._stencilOpDepthFail === value) {
  10242. return;
  10243. }
  10244. this._stencilOpDepthFail = value;
  10245. this._isStencilOpDirty = true;
  10246. },
  10247. enumerable: true,
  10248. configurable: true
  10249. });
  10250. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10251. get: function () {
  10252. return this._stencilOpStencilDepthPass;
  10253. },
  10254. set: function (value) {
  10255. if (this._stencilOpStencilDepthPass === value) {
  10256. return;
  10257. }
  10258. this._stencilOpStencilDepthPass = value;
  10259. this._isStencilOpDirty = true;
  10260. },
  10261. enumerable: true,
  10262. configurable: true
  10263. });
  10264. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10265. get: function () {
  10266. return this._stencilMask;
  10267. },
  10268. set: function (value) {
  10269. if (this._stencilMask === value) {
  10270. return;
  10271. }
  10272. this._stencilMask = value;
  10273. this._isStencilMaskDirty = true;
  10274. },
  10275. enumerable: true,
  10276. configurable: true
  10277. });
  10278. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10279. get: function () {
  10280. return this._stencilTest;
  10281. },
  10282. set: function (value) {
  10283. if (this._stencilTest === value) {
  10284. return;
  10285. }
  10286. this._stencilTest = value;
  10287. this._isStencilTestDirty = true;
  10288. },
  10289. enumerable: true,
  10290. configurable: true
  10291. });
  10292. _StencilState.prototype.reset = function () {
  10293. this._stencilTest = false;
  10294. this._stencilMask = 0xFF;
  10295. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10296. this._stencilFuncRef = 1;
  10297. this._stencilFuncMask = 0xFF;
  10298. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10299. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10300. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10301. this._isStencilTestDirty = true;
  10302. this._isStencilMaskDirty = true;
  10303. this._isStencilFuncDirty = true;
  10304. this._isStencilOpDirty = true;
  10305. };
  10306. _StencilState.prototype.apply = function (gl) {
  10307. if (!this.isDirty) {
  10308. return;
  10309. }
  10310. // Stencil test
  10311. if (this._isStencilTestDirty) {
  10312. if (this.stencilTest) {
  10313. gl.enable(gl.STENCIL_TEST);
  10314. }
  10315. else {
  10316. gl.disable(gl.STENCIL_TEST);
  10317. }
  10318. this._isStencilTestDirty = false;
  10319. }
  10320. // Stencil mask
  10321. if (this._isStencilMaskDirty) {
  10322. gl.stencilMask(this.stencilMask);
  10323. this._isStencilMaskDirty = false;
  10324. }
  10325. // Stencil func
  10326. if (this._isStencilFuncDirty) {
  10327. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10328. this._isStencilFuncDirty = false;
  10329. }
  10330. // Stencil op
  10331. if (this._isStencilOpDirty) {
  10332. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10333. this._isStencilOpDirty = false;
  10334. }
  10335. };
  10336. return _StencilState;
  10337. }());
  10338. BABYLON._StencilState = _StencilState;
  10339. })(BABYLON || (BABYLON = {}));
  10340. //# sourceMappingURL=babylon.stencilState.js.map
  10341. "use strict";
  10342. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10343. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10344. s = arguments[i];
  10345. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10346. t[p] = s[p];
  10347. }
  10348. return t;
  10349. };
  10350. var BABYLON;
  10351. (function (BABYLON) {
  10352. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10353. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10354. };
  10355. var compileRawShader = function (gl, source, type) {
  10356. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10357. gl.shaderSource(shader, source);
  10358. gl.compileShader(shader);
  10359. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10360. var log = gl.getShaderInfoLog(shader);
  10361. if (log) {
  10362. throw new Error(log);
  10363. }
  10364. }
  10365. if (!shader) {
  10366. throw new Error("Something went wrong while compile the shader.");
  10367. }
  10368. return shader;
  10369. };
  10370. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10371. var magFilter = gl.NEAREST;
  10372. var minFilter = gl.NEAREST;
  10373. switch (samplingMode) {
  10374. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10375. magFilter = gl.LINEAR;
  10376. if (generateMipMaps) {
  10377. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10378. }
  10379. else {
  10380. minFilter = gl.LINEAR;
  10381. }
  10382. break;
  10383. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10384. magFilter = gl.LINEAR;
  10385. if (generateMipMaps) {
  10386. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10387. }
  10388. else {
  10389. minFilter = gl.LINEAR;
  10390. }
  10391. break;
  10392. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10393. magFilter = gl.NEAREST;
  10394. if (generateMipMaps) {
  10395. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10396. }
  10397. else {
  10398. minFilter = gl.NEAREST;
  10399. }
  10400. break;
  10401. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10402. magFilter = gl.NEAREST;
  10403. if (generateMipMaps) {
  10404. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10405. }
  10406. else {
  10407. minFilter = gl.NEAREST;
  10408. }
  10409. break;
  10410. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10411. magFilter = gl.NEAREST;
  10412. if (generateMipMaps) {
  10413. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10414. }
  10415. else {
  10416. minFilter = gl.LINEAR;
  10417. }
  10418. break;
  10419. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10420. magFilter = gl.NEAREST;
  10421. if (generateMipMaps) {
  10422. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10423. }
  10424. else {
  10425. minFilter = gl.LINEAR;
  10426. }
  10427. break;
  10428. case BABYLON.Texture.NEAREST_LINEAR:
  10429. magFilter = gl.NEAREST;
  10430. minFilter = gl.LINEAR;
  10431. break;
  10432. case BABYLON.Texture.NEAREST_NEAREST:
  10433. magFilter = gl.NEAREST;
  10434. minFilter = gl.NEAREST;
  10435. break;
  10436. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10437. magFilter = gl.LINEAR;
  10438. if (generateMipMaps) {
  10439. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10440. }
  10441. else {
  10442. minFilter = gl.NEAREST;
  10443. }
  10444. break;
  10445. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10446. magFilter = gl.LINEAR;
  10447. if (generateMipMaps) {
  10448. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10449. }
  10450. else {
  10451. minFilter = gl.NEAREST;
  10452. }
  10453. break;
  10454. case BABYLON.Texture.LINEAR_LINEAR:
  10455. magFilter = gl.LINEAR;
  10456. minFilter = gl.LINEAR;
  10457. break;
  10458. case BABYLON.Texture.LINEAR_NEAREST:
  10459. magFilter = gl.LINEAR;
  10460. minFilter = gl.NEAREST;
  10461. break;
  10462. }
  10463. return {
  10464. min: minFilter,
  10465. mag: magFilter
  10466. };
  10467. };
  10468. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10469. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10470. var img;
  10471. var onload = function () {
  10472. loadedImages[index] = img;
  10473. loadedImages._internalCount++;
  10474. if (scene) {
  10475. scene._removePendingData(img);
  10476. }
  10477. if (loadedImages._internalCount === 6) {
  10478. onfinish(loadedImages);
  10479. }
  10480. };
  10481. var onerror = function (message, exception) {
  10482. if (scene) {
  10483. scene._removePendingData(img);
  10484. }
  10485. if (onErrorCallBack) {
  10486. onErrorCallBack(message, exception);
  10487. }
  10488. };
  10489. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10490. if (scene) {
  10491. scene._addPendingData(img);
  10492. }
  10493. };
  10494. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10495. if (onError === void 0) { onError = null; }
  10496. var loadedImages = [];
  10497. loadedImages._internalCount = 0;
  10498. for (var index = 0; index < 6; index++) {
  10499. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10500. }
  10501. };
  10502. var BufferPointer = /** @class */ (function () {
  10503. function BufferPointer() {
  10504. }
  10505. return BufferPointer;
  10506. }());
  10507. var InstancingAttributeInfo = /** @class */ (function () {
  10508. function InstancingAttributeInfo() {
  10509. }
  10510. return InstancingAttributeInfo;
  10511. }());
  10512. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10513. /**
  10514. * Define options used to create a render target texture
  10515. */
  10516. var RenderTargetCreationOptions = /** @class */ (function () {
  10517. function RenderTargetCreationOptions() {
  10518. }
  10519. return RenderTargetCreationOptions;
  10520. }());
  10521. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10522. /**
  10523. * Define options used to create a depth texture
  10524. */
  10525. var DepthTextureCreationOptions = /** @class */ (function () {
  10526. function DepthTextureCreationOptions() {
  10527. }
  10528. return DepthTextureCreationOptions;
  10529. }());
  10530. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10531. /**
  10532. * Regroup several parameters relative to the browser in use
  10533. */
  10534. var EngineCapabilities = /** @class */ (function () {
  10535. function EngineCapabilities() {
  10536. }
  10537. return EngineCapabilities;
  10538. }());
  10539. BABYLON.EngineCapabilities = EngineCapabilities;
  10540. /**
  10541. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10542. */
  10543. var Engine = /** @class */ (function () {
  10544. /**
  10545. * @constructor
  10546. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10547. * @param antialias defines enable antialiasing (default: false)
  10548. * @param options defines further options to be sent to the getContext() function
  10549. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10550. */
  10551. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10552. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10553. var _this = this;
  10554. // Public members
  10555. this.forcePOTTextures = false;
  10556. this.isFullscreen = false;
  10557. this.isPointerLock = false;
  10558. this.cullBackFaces = true;
  10559. this.renderEvenInBackground = true;
  10560. this.preventCacheWipeBetweenFrames = false;
  10561. // To enable/disable IDB support and avoid XHR on .manifest
  10562. this.enableOfflineSupport = false;
  10563. this.scenes = new Array();
  10564. this.postProcesses = new Array();
  10565. // Observables
  10566. /**
  10567. * Observable event triggered each time the rendering canvas is resized
  10568. */
  10569. this.onResizeObservable = new BABYLON.Observable();
  10570. /**
  10571. * Observable event triggered each time the canvas loses focus
  10572. */
  10573. this.onCanvasBlurObservable = new BABYLON.Observable();
  10574. /**
  10575. * Observable event triggered each time the canvas gains focus
  10576. */
  10577. this.onCanvasFocusObservable = new BABYLON.Observable();
  10578. /**
  10579. * Observable event triggered each time the canvas receives pointerout event
  10580. */
  10581. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10582. /**
  10583. * Observable event triggered before each texture is initialized
  10584. */
  10585. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10586. //WebVR
  10587. this._vrDisplay = undefined;
  10588. this._vrSupported = false;
  10589. this._vrExclusivePointerMode = false;
  10590. // Uniform buffers list
  10591. this.disableUniformBuffers = false;
  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. this._badOS = false;
  10613. this._badDesktopOS = false;
  10614. /**
  10615. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10616. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10617. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10618. */
  10619. this.disableTextureBindingOptimization = false;
  10620. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10621. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10622. this.onVRRequestPresentStart = new BABYLON.Observable();
  10623. this._colorWrite = true;
  10624. this._drawCalls = new BABYLON.PerfCounter();
  10625. this._textureCollisions = new BABYLON.PerfCounter();
  10626. this._renderingQueueLaunched = false;
  10627. this._activeRenderLoops = new Array();
  10628. // Deterministic lockstepMaxSteps
  10629. this._deterministicLockstep = false;
  10630. this._lockstepMaxSteps = 4;
  10631. // Lost context
  10632. this.onContextLostObservable = new BABYLON.Observable();
  10633. this.onContextRestoredObservable = new BABYLON.Observable();
  10634. this._contextWasLost = false;
  10635. this._doNotHandleContextLost = false;
  10636. // FPS
  10637. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10638. this._fps = 60;
  10639. this._deltaTime = 0;
  10640. /**
  10641. * Turn this value on if you want to pause FPS computation when in background
  10642. */
  10643. this.disablePerformanceMonitorInBackground = false;
  10644. // States
  10645. this._depthCullingState = new BABYLON._DepthCullingState();
  10646. this._stencilState = new BABYLON._StencilState();
  10647. this._alphaState = new BABYLON._AlphaState();
  10648. this._alphaMode = Engine.ALPHA_DISABLE;
  10649. // Cache
  10650. this._internalTexturesCache = new Array();
  10651. this._activeChannel = 0;
  10652. this._currentTextureChannel = -1;
  10653. this._boundTexturesCache = {};
  10654. this._compiledEffects = {};
  10655. this._vertexAttribArraysEnabled = [];
  10656. this._uintIndicesCurrentlySet = false;
  10657. this._currentBoundBuffer = new Array();
  10658. this._currentBufferPointers = new Array();
  10659. this._currentInstanceLocations = new Array();
  10660. this._currentInstanceBuffers = new Array();
  10661. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10662. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10663. this._vaoRecordInProgress = false;
  10664. this._mustWipeVertexAttributes = false;
  10665. this._nextFreeTextureSlots = new Array();
  10666. this._maxSimultaneousTextures = 0;
  10667. this._activeRequests = new Array();
  10668. // Hardware supported Compressed Textures
  10669. this._texturesSupported = new Array();
  10670. this._onVRFullScreenTriggered = function () {
  10671. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10672. //get the old size before we change
  10673. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10674. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10675. //get the width and height, change the render size
  10676. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10677. _this.setHardwareScalingLevel(1);
  10678. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10679. }
  10680. else {
  10681. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10682. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10683. }
  10684. };
  10685. this._boundUniforms = {};
  10686. // Register promises
  10687. BABYLON.PromisePolyfill.Apply();
  10688. var canvas = null;
  10689. Engine.Instances.push(this);
  10690. if (!canvasOrContext) {
  10691. return;
  10692. }
  10693. options = options || {};
  10694. if (canvasOrContext.getContext) {
  10695. canvas = canvasOrContext;
  10696. this._renderingCanvas = canvas;
  10697. if (antialias != null) {
  10698. options.antialias = antialias;
  10699. }
  10700. if (options.deterministicLockstep === undefined) {
  10701. options.deterministicLockstep = false;
  10702. }
  10703. if (options.lockstepMaxSteps === undefined) {
  10704. options.lockstepMaxSteps = 4;
  10705. }
  10706. if (options.preserveDrawingBuffer === undefined) {
  10707. options.preserveDrawingBuffer = false;
  10708. }
  10709. if (options.audioEngine === undefined) {
  10710. options.audioEngine = true;
  10711. }
  10712. if (options.stencil === undefined) {
  10713. options.stencil = true;
  10714. }
  10715. this._deterministicLockstep = options.deterministicLockstep;
  10716. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10717. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10718. // Exceptions
  10719. if (navigator && navigator.userAgent) {
  10720. var ua = navigator.userAgent;
  10721. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10722. var exception = _a[_i];
  10723. var key = exception.key;
  10724. var targets = exception.targets;
  10725. if (ua.indexOf(key) > -1) {
  10726. if (exception.capture && exception.captureConstraint) {
  10727. var capture = exception.capture;
  10728. var constraint = exception.captureConstraint;
  10729. var regex = new RegExp(capture);
  10730. var matches = regex.exec(ua);
  10731. if (matches && matches.length > 0) {
  10732. var capturedValue = parseInt(matches[matches.length - 1]);
  10733. if (capturedValue >= constraint) {
  10734. continue;
  10735. }
  10736. }
  10737. }
  10738. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10739. var target = targets_1[_b];
  10740. switch (target) {
  10741. case "uniformBuffer":
  10742. this.disableUniformBuffers = true;
  10743. break;
  10744. case "textureBindingOptimization":
  10745. this.disableTextureBindingOptimization = true;
  10746. break;
  10747. }
  10748. }
  10749. }
  10750. }
  10751. }
  10752. // GL
  10753. if (!options.disableWebGL2Support) {
  10754. try {
  10755. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10756. if (this._gl) {
  10757. this._webGLVersion = 2.0;
  10758. }
  10759. }
  10760. catch (e) {
  10761. // Do nothing
  10762. }
  10763. }
  10764. if (!this._gl) {
  10765. if (!canvas) {
  10766. throw new Error("The provided canvas is null or undefined.");
  10767. }
  10768. try {
  10769. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10770. }
  10771. catch (e) {
  10772. throw new Error("WebGL not supported");
  10773. }
  10774. }
  10775. if (!this._gl) {
  10776. throw new Error("WebGL not supported");
  10777. }
  10778. this._onCanvasFocus = function () {
  10779. _this.onCanvasFocusObservable.notifyObservers(_this);
  10780. };
  10781. this._onCanvasBlur = function () {
  10782. _this.onCanvasBlurObservable.notifyObservers(_this);
  10783. };
  10784. canvas.addEventListener("focus", this._onCanvasFocus);
  10785. canvas.addEventListener("blur", this._onCanvasBlur);
  10786. this._onBlur = function () {
  10787. if (_this.disablePerformanceMonitorInBackground) {
  10788. _this._performanceMonitor.disable();
  10789. }
  10790. _this._windowIsBackground = true;
  10791. };
  10792. this._onFocus = function () {
  10793. if (_this.disablePerformanceMonitorInBackground) {
  10794. _this._performanceMonitor.enable();
  10795. }
  10796. _this._windowIsBackground = false;
  10797. };
  10798. this._onCanvasPointerOut = function (ev) {
  10799. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10800. };
  10801. window.addEventListener("blur", this._onBlur);
  10802. window.addEventListener("focus", this._onFocus);
  10803. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10804. // Context lost
  10805. if (!this._doNotHandleContextLost) {
  10806. this._onContextLost = function (evt) {
  10807. evt.preventDefault();
  10808. _this._contextWasLost = true;
  10809. BABYLON.Tools.Warn("WebGL context lost.");
  10810. _this.onContextLostObservable.notifyObservers(_this);
  10811. };
  10812. this._onContextRestored = function (evt) {
  10813. // Adding a timeout to avoid race condition at browser level
  10814. setTimeout(function () {
  10815. // Rebuild gl context
  10816. _this._initGLContext();
  10817. // Rebuild effects
  10818. _this._rebuildEffects();
  10819. // Rebuild textures
  10820. _this._rebuildInternalTextures();
  10821. // Rebuild buffers
  10822. _this._rebuildBuffers();
  10823. // Cache
  10824. _this.wipeCaches(true);
  10825. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10826. _this.onContextRestoredObservable.notifyObservers(_this);
  10827. _this._contextWasLost = false;
  10828. }, 0);
  10829. };
  10830. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10831. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10832. }
  10833. }
  10834. else {
  10835. this._gl = canvasOrContext;
  10836. this._renderingCanvas = this._gl.canvas;
  10837. if (this._gl.renderbufferStorageMultisample) {
  10838. this._webGLVersion = 2.0;
  10839. }
  10840. options.stencil = this._gl.getContextAttributes().stencil;
  10841. }
  10842. // Viewport
  10843. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10844. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10845. this.resize();
  10846. this._isStencilEnable = options.stencil ? true : false;
  10847. this._initGLContext();
  10848. if (canvas) {
  10849. // Fullscreen
  10850. this._onFullscreenChange = function () {
  10851. if (document.fullscreen !== undefined) {
  10852. _this.isFullscreen = document.fullscreen;
  10853. }
  10854. else if (document.mozFullScreen !== undefined) {
  10855. _this.isFullscreen = document.mozFullScreen;
  10856. }
  10857. else if (document.webkitIsFullScreen !== undefined) {
  10858. _this.isFullscreen = document.webkitIsFullScreen;
  10859. }
  10860. else if (document.msIsFullScreen !== undefined) {
  10861. _this.isFullscreen = document.msIsFullScreen;
  10862. }
  10863. // Pointer lock
  10864. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10865. canvas.requestPointerLock = canvas.requestPointerLock ||
  10866. canvas.msRequestPointerLock ||
  10867. canvas.mozRequestPointerLock ||
  10868. canvas.webkitRequestPointerLock;
  10869. if (canvas.requestPointerLock) {
  10870. canvas.requestPointerLock();
  10871. }
  10872. }
  10873. };
  10874. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10875. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10876. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10877. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10878. // Pointer lock
  10879. this._onPointerLockChange = function () {
  10880. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10881. document.webkitPointerLockElement === canvas ||
  10882. document.msPointerLockElement === canvas ||
  10883. document.pointerLockElement === canvas);
  10884. };
  10885. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10886. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10887. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10888. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10889. this._onVRDisplayPointerRestricted = function () {
  10890. if (canvas) {
  10891. canvas.requestPointerLock();
  10892. }
  10893. };
  10894. this._onVRDisplayPointerUnrestricted = function () {
  10895. document.exitPointerLock();
  10896. };
  10897. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10898. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10899. }
  10900. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10901. Engine.audioEngine = new BABYLON.AudioEngine();
  10902. }
  10903. // Prepare buffer pointers
  10904. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10905. this._currentBufferPointers[i] = new BufferPointer();
  10906. }
  10907. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10908. // Load WebVR Devices
  10909. if (options.autoEnableWebVR) {
  10910. this.initWebVR();
  10911. }
  10912. // Detect if we are running on a faulty buggy OS.
  10913. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10914. // Detect if we are running on a faulty buggy desktop OS.
  10915. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10916. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10917. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10918. }
  10919. Object.defineProperty(Engine, "LastCreatedEngine", {
  10920. get: function () {
  10921. if (Engine.Instances.length === 0) {
  10922. return null;
  10923. }
  10924. return Engine.Instances[Engine.Instances.length - 1];
  10925. },
  10926. enumerable: true,
  10927. configurable: true
  10928. });
  10929. Object.defineProperty(Engine, "LastCreatedScene", {
  10930. get: function () {
  10931. var lastCreatedEngine = Engine.LastCreatedEngine;
  10932. if (!lastCreatedEngine) {
  10933. return null;
  10934. }
  10935. if (lastCreatedEngine.scenes.length === 0) {
  10936. return null;
  10937. }
  10938. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. /**
  10944. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10945. */
  10946. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10947. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10948. var engine = Engine.Instances[engineIndex];
  10949. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10950. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10951. }
  10952. }
  10953. };
  10954. Object.defineProperty(Engine, "NEVER", {
  10955. get: function () {
  10956. return Engine._NEVER;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(Engine, "ALWAYS", {
  10962. get: function () {
  10963. return Engine._ALWAYS;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "LESS", {
  10969. get: function () {
  10970. return Engine._LESS;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(Engine, "EQUAL", {
  10976. get: function () {
  10977. return Engine._EQUAL;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "LEQUAL", {
  10983. get: function () {
  10984. return Engine._LEQUAL;
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(Engine, "GREATER", {
  10990. get: function () {
  10991. return Engine._GREATER;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(Engine, "GEQUAL", {
  10997. get: function () {
  10998. return Engine._GEQUAL;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(Engine, "NOTEQUAL", {
  11004. get: function () {
  11005. return Engine._NOTEQUAL;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(Engine, "KEEP", {
  11011. get: function () {
  11012. return Engine._KEEP;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(Engine, "REPLACE", {
  11018. get: function () {
  11019. return Engine._REPLACE;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(Engine, "INCR", {
  11025. get: function () {
  11026. return Engine._INCR;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(Engine, "DECR", {
  11032. get: function () {
  11033. return Engine._DECR;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(Engine, "INVERT", {
  11039. get: function () {
  11040. return Engine._INVERT;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Engine, "INCR_WRAP", {
  11046. get: function () {
  11047. return Engine._INCR_WRAP;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Engine, "DECR_WRAP", {
  11053. get: function () {
  11054. return Engine._DECR_WRAP;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11060. get: function () {
  11061. return Engine._ALPHA_DISABLE;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11067. get: function () {
  11068. return Engine._ALPHA_ONEONE;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(Engine, "ALPHA_ADD", {
  11074. get: function () {
  11075. return Engine._ALPHA_ADD;
  11076. },
  11077. enumerable: true,
  11078. configurable: true
  11079. });
  11080. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11081. get: function () {
  11082. return Engine._ALPHA_COMBINE;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11088. get: function () {
  11089. return Engine._ALPHA_SUBTRACT;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11095. get: function () {
  11096. return Engine._ALPHA_MULTIPLY;
  11097. },
  11098. enumerable: true,
  11099. configurable: true
  11100. });
  11101. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11102. get: function () {
  11103. return Engine._ALPHA_MAXIMIZED;
  11104. },
  11105. enumerable: true,
  11106. configurable: true
  11107. });
  11108. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11109. get: function () {
  11110. return Engine._ALPHA_PREMULTIPLIED;
  11111. },
  11112. enumerable: true,
  11113. configurable: true
  11114. });
  11115. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11116. get: function () {
  11117. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11118. },
  11119. enumerable: true,
  11120. configurable: true
  11121. });
  11122. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11123. get: function () {
  11124. return Engine._ALPHA_INTERPOLATE;
  11125. },
  11126. enumerable: true,
  11127. configurable: true
  11128. });
  11129. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11130. get: function () {
  11131. return Engine._ALPHA_SCREENMODE;
  11132. },
  11133. enumerable: true,
  11134. configurable: true
  11135. });
  11136. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11137. get: function () {
  11138. return Engine._DELAYLOADSTATE_NONE;
  11139. },
  11140. enumerable: true,
  11141. configurable: true
  11142. });
  11143. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11144. get: function () {
  11145. return Engine._DELAYLOADSTATE_LOADED;
  11146. },
  11147. enumerable: true,
  11148. configurable: true
  11149. });
  11150. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11151. get: function () {
  11152. return Engine._DELAYLOADSTATE_LOADING;
  11153. },
  11154. enumerable: true,
  11155. configurable: true
  11156. });
  11157. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11158. get: function () {
  11159. return Engine._DELAYLOADSTATE_NOTLOADED;
  11160. },
  11161. enumerable: true,
  11162. configurable: true
  11163. });
  11164. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11165. get: function () {
  11166. return Engine._TEXTUREFORMAT_ALPHA;
  11167. },
  11168. enumerable: true,
  11169. configurable: true
  11170. });
  11171. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11172. get: function () {
  11173. return Engine._TEXTUREFORMAT_LUMINANCE;
  11174. },
  11175. enumerable: true,
  11176. configurable: true
  11177. });
  11178. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11179. /**
  11180. * R32F
  11181. */
  11182. get: function () {
  11183. return Engine._TEXTUREFORMAT_R32F;
  11184. },
  11185. enumerable: true,
  11186. configurable: true
  11187. });
  11188. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11189. /**
  11190. * RG32F
  11191. */
  11192. get: function () {
  11193. return Engine._TEXTUREFORMAT_RG32F;
  11194. },
  11195. enumerable: true,
  11196. configurable: true
  11197. });
  11198. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11199. /**
  11200. * RGB32F
  11201. */
  11202. get: function () {
  11203. return Engine._TEXTUREFORMAT_RGB32F;
  11204. },
  11205. enumerable: true,
  11206. configurable: true
  11207. });
  11208. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11209. /**
  11210. * RGBA32F
  11211. */
  11212. get: function () {
  11213. return Engine._TEXTUREFORMAT_RGBA32F;
  11214. },
  11215. enumerable: true,
  11216. configurable: true
  11217. });
  11218. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11219. get: function () {
  11220. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11221. },
  11222. enumerable: true,
  11223. configurable: true
  11224. });
  11225. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11226. get: function () {
  11227. return Engine._TEXTUREFORMAT_RGB;
  11228. },
  11229. enumerable: true,
  11230. configurable: true
  11231. });
  11232. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11233. get: function () {
  11234. return Engine._TEXTUREFORMAT_RGBA;
  11235. },
  11236. enumerable: true,
  11237. configurable: true
  11238. });
  11239. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11240. get: function () {
  11241. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11242. },
  11243. enumerable: true,
  11244. configurable: true
  11245. });
  11246. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11247. get: function () {
  11248. return Engine._TEXTURETYPE_FLOAT;
  11249. },
  11250. enumerable: true,
  11251. configurable: true
  11252. });
  11253. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11254. get: function () {
  11255. return Engine._TEXTURETYPE_HALF_FLOAT;
  11256. },
  11257. enumerable: true,
  11258. configurable: true
  11259. });
  11260. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11261. get: function () {
  11262. return Engine._SCALEMODE_FLOOR;
  11263. },
  11264. enumerable: true,
  11265. configurable: true
  11266. });
  11267. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11268. get: function () {
  11269. return Engine._SCALEMODE_NEAREST;
  11270. },
  11271. enumerable: true,
  11272. configurable: true
  11273. });
  11274. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11275. get: function () {
  11276. return Engine._SCALEMODE_CEILING;
  11277. },
  11278. enumerable: true,
  11279. configurable: true
  11280. });
  11281. Object.defineProperty(Engine, "Version", {
  11282. get: function () {
  11283. return "3.2.0-beta.1";
  11284. },
  11285. enumerable: true,
  11286. configurable: true
  11287. });
  11288. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11289. get: function () {
  11290. return this._vrExclusivePointerMode;
  11291. },
  11292. enumerable: true,
  11293. configurable: true
  11294. });
  11295. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11296. get: function () {
  11297. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11298. },
  11299. enumerable: true,
  11300. configurable: true
  11301. });
  11302. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11303. get: function () {
  11304. return this._webGLVersion < 2 || this.forcePOTTextures;
  11305. },
  11306. enumerable: true,
  11307. configurable: true
  11308. });
  11309. Object.defineProperty(Engine.prototype, "badOS", {
  11310. get: function () {
  11311. return this._badOS;
  11312. },
  11313. enumerable: true,
  11314. configurable: true
  11315. });
  11316. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11317. get: function () {
  11318. return this._badDesktopOS;
  11319. },
  11320. enumerable: true,
  11321. configurable: true
  11322. });
  11323. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11324. get: function () {
  11325. return this._performanceMonitor;
  11326. },
  11327. enumerable: true,
  11328. configurable: true
  11329. });
  11330. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11331. get: function () {
  11332. return this._texturesSupported;
  11333. },
  11334. enumerable: true,
  11335. configurable: true
  11336. });
  11337. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11338. get: function () {
  11339. return this._textureFormatInUse;
  11340. },
  11341. enumerable: true,
  11342. configurable: true
  11343. });
  11344. Object.defineProperty(Engine.prototype, "currentViewport", {
  11345. get: function () {
  11346. return this._cachedViewport;
  11347. },
  11348. enumerable: true,
  11349. configurable: true
  11350. });
  11351. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11352. // Empty texture
  11353. get: function () {
  11354. if (!this._emptyTexture) {
  11355. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11356. }
  11357. return this._emptyTexture;
  11358. },
  11359. enumerable: true,
  11360. configurable: true
  11361. });
  11362. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11363. get: function () {
  11364. if (!this._emptyTexture3D) {
  11365. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11366. }
  11367. return this._emptyTexture3D;
  11368. },
  11369. enumerable: true,
  11370. configurable: true
  11371. });
  11372. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11373. get: function () {
  11374. if (!this._emptyCubeTexture) {
  11375. var faceData = new Uint8Array(4);
  11376. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11377. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11378. }
  11379. return this._emptyCubeTexture;
  11380. },
  11381. enumerable: true,
  11382. configurable: true
  11383. });
  11384. Engine.prototype._rebuildInternalTextures = function () {
  11385. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11386. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11387. var internalTexture = currentState_1[_i];
  11388. internalTexture._rebuild();
  11389. }
  11390. };
  11391. Engine.prototype._rebuildEffects = function () {
  11392. for (var key in this._compiledEffects) {
  11393. var effect = this._compiledEffects[key];
  11394. effect._prepareEffect();
  11395. }
  11396. BABYLON.Effect.ResetCache();
  11397. };
  11398. Engine.prototype._rebuildBuffers = function () {
  11399. // Index / Vertex
  11400. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11401. var scene = _a[_i];
  11402. scene.resetCachedMaterial();
  11403. scene._rebuildGeometries();
  11404. scene._rebuildTextures();
  11405. }
  11406. // Uniforms
  11407. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11408. var uniformBuffer = _c[_b];
  11409. uniformBuffer._rebuild();
  11410. }
  11411. };
  11412. Engine.prototype._initGLContext = function () {
  11413. // Caps
  11414. this._caps = new EngineCapabilities();
  11415. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11416. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11417. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11418. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11419. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11420. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11421. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11422. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11423. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11424. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11425. // Infos
  11426. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11427. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11428. if (rendererInfo != null) {
  11429. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11430. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11431. }
  11432. if (!this._glVendor) {
  11433. this._glVendor = "Unknown vendor";
  11434. }
  11435. if (!this._glRenderer) {
  11436. this._glRenderer = "Unknown renderer";
  11437. }
  11438. // Constants
  11439. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11440. if (this._gl.RGBA16F !== 0x881A) {
  11441. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11442. }
  11443. if (this._gl.RGBA32F !== 0x8814) {
  11444. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11445. }
  11446. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11447. this._gl.DEPTH24_STENCIL8 = 35056;
  11448. }
  11449. // Extensions
  11450. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11451. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11452. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11453. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11454. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11455. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11456. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11457. 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');
  11458. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11459. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11460. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11461. this._caps.highPrecisionShaderSupported = true;
  11462. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11463. if (this._caps.timerQuery) {
  11464. if (this._webGLVersion === 1) {
  11465. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11466. }
  11467. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11468. }
  11469. // Checks if some of the format renders first to allow the use of webgl inspector.
  11470. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11471. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11472. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11473. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11474. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11475. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11476. if (this._webGLVersion > 1) {
  11477. this._gl.HALF_FLOAT_OES = 0x140B;
  11478. }
  11479. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11480. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11481. // Draw buffers
  11482. if (this._webGLVersion > 1) {
  11483. this._caps.drawBuffersExtension = true;
  11484. }
  11485. else {
  11486. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11487. if (drawBuffersExtension !== null) {
  11488. this._caps.drawBuffersExtension = true;
  11489. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11490. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11491. for (var i = 0; i < 16; i++) {
  11492. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11493. }
  11494. }
  11495. else {
  11496. this._caps.drawBuffersExtension = false;
  11497. }
  11498. }
  11499. // Depth Texture
  11500. if (this._webGLVersion > 1) {
  11501. this._caps.depthTextureExtension = true;
  11502. }
  11503. else {
  11504. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11505. if (depthTextureExtension != null) {
  11506. this._caps.depthTextureExtension = true;
  11507. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11508. }
  11509. }
  11510. // Vertex array object
  11511. if (this._webGLVersion > 1) {
  11512. this._caps.vertexArrayObject = true;
  11513. }
  11514. else {
  11515. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11516. if (vertexArrayObjectExtension != null) {
  11517. this._caps.vertexArrayObject = true;
  11518. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11519. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11520. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11521. }
  11522. else {
  11523. this._caps.vertexArrayObject = false;
  11524. }
  11525. }
  11526. // Instances count
  11527. if (this._webGLVersion > 1) {
  11528. this._caps.instancedArrays = true;
  11529. }
  11530. else {
  11531. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11532. if (instanceExtension != null) {
  11533. this._caps.instancedArrays = true;
  11534. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11535. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11536. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11537. }
  11538. else {
  11539. this._caps.instancedArrays = false;
  11540. }
  11541. }
  11542. // Intelligently add supported compressed formats in order to check for.
  11543. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11544. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11545. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11546. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11547. if (this._caps.astc)
  11548. this.texturesSupported.push('-astc.ktx');
  11549. if (this._caps.s3tc)
  11550. this.texturesSupported.push('-dxt.ktx');
  11551. if (this._caps.pvrtc)
  11552. this.texturesSupported.push('-pvrtc.ktx');
  11553. if (this._caps.etc2)
  11554. this.texturesSupported.push('-etc2.ktx');
  11555. if (this._caps.etc1)
  11556. this.texturesSupported.push('-etc1.ktx');
  11557. if (this._gl.getShaderPrecisionFormat) {
  11558. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11559. if (highp) {
  11560. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11561. }
  11562. }
  11563. // Depth buffer
  11564. this.setDepthBuffer(true);
  11565. this.setDepthFunctionToLessOrEqual();
  11566. this.setDepthWrite(true);
  11567. // Texture maps
  11568. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11569. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11570. this._nextFreeTextureSlots.push(slot);
  11571. }
  11572. };
  11573. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11574. get: function () {
  11575. return this._webGLVersion;
  11576. },
  11577. enumerable: true,
  11578. configurable: true
  11579. });
  11580. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11581. /**
  11582. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11583. */
  11584. get: function () {
  11585. return this._isStencilEnable;
  11586. },
  11587. enumerable: true,
  11588. configurable: true
  11589. });
  11590. Engine.prototype._prepareWorkingCanvas = function () {
  11591. if (this._workingCanvas) {
  11592. return;
  11593. }
  11594. this._workingCanvas = document.createElement("canvas");
  11595. var context = this._workingCanvas.getContext("2d");
  11596. if (context) {
  11597. this._workingContext = context;
  11598. }
  11599. };
  11600. Engine.prototype.resetTextureCache = function () {
  11601. for (var key in this._boundTexturesCache) {
  11602. var boundTexture = this._boundTexturesCache[key];
  11603. if (boundTexture) {
  11604. this._removeDesignatedSlot(boundTexture);
  11605. }
  11606. this._boundTexturesCache[key] = null;
  11607. }
  11608. if (!this.disableTextureBindingOptimization) {
  11609. this._nextFreeTextureSlots = [];
  11610. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11611. this._nextFreeTextureSlots.push(slot);
  11612. }
  11613. }
  11614. this._currentTextureChannel = -1;
  11615. };
  11616. Engine.prototype.isDeterministicLockStep = function () {
  11617. return this._deterministicLockstep;
  11618. };
  11619. Engine.prototype.getLockstepMaxSteps = function () {
  11620. return this._lockstepMaxSteps;
  11621. };
  11622. Engine.prototype.getGlInfo = function () {
  11623. return {
  11624. vendor: this._glVendor,
  11625. renderer: this._glRenderer,
  11626. version: this._glVersion
  11627. };
  11628. };
  11629. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11630. if (useScreen === void 0) { useScreen = false; }
  11631. var viewport = camera.viewport;
  11632. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11633. };
  11634. Engine.prototype.getRenderWidth = function (useScreen) {
  11635. if (useScreen === void 0) { useScreen = false; }
  11636. if (!useScreen && this._currentRenderTarget) {
  11637. return this._currentRenderTarget.width;
  11638. }
  11639. return this._gl.drawingBufferWidth;
  11640. };
  11641. Engine.prototype.getRenderHeight = function (useScreen) {
  11642. if (useScreen === void 0) { useScreen = false; }
  11643. if (!useScreen && this._currentRenderTarget) {
  11644. return this._currentRenderTarget.height;
  11645. }
  11646. return this._gl.drawingBufferHeight;
  11647. };
  11648. Engine.prototype.getRenderingCanvas = function () {
  11649. return this._renderingCanvas;
  11650. };
  11651. Engine.prototype.getRenderingCanvasClientRect = function () {
  11652. if (!this._renderingCanvas) {
  11653. return null;
  11654. }
  11655. return this._renderingCanvas.getBoundingClientRect();
  11656. };
  11657. Engine.prototype.setHardwareScalingLevel = function (level) {
  11658. this._hardwareScalingLevel = level;
  11659. this.resize();
  11660. };
  11661. Engine.prototype.getHardwareScalingLevel = function () {
  11662. return this._hardwareScalingLevel;
  11663. };
  11664. Engine.prototype.getLoadedTexturesCache = function () {
  11665. return this._internalTexturesCache;
  11666. };
  11667. Engine.prototype.getCaps = function () {
  11668. return this._caps;
  11669. };
  11670. Object.defineProperty(Engine.prototype, "drawCalls", {
  11671. /** The number of draw calls submitted last frame */
  11672. get: function () {
  11673. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11674. return 0;
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11680. get: function () {
  11681. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11682. return null;
  11683. },
  11684. enumerable: true,
  11685. configurable: true
  11686. });
  11687. Engine.prototype.getDepthFunction = function () {
  11688. return this._depthCullingState.depthFunc;
  11689. };
  11690. Engine.prototype.setDepthFunction = function (depthFunc) {
  11691. this._depthCullingState.depthFunc = depthFunc;
  11692. };
  11693. Engine.prototype.setDepthFunctionToGreater = function () {
  11694. this._depthCullingState.depthFunc = this._gl.GREATER;
  11695. };
  11696. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11697. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11698. };
  11699. Engine.prototype.setDepthFunctionToLess = function () {
  11700. this._depthCullingState.depthFunc = this._gl.LESS;
  11701. };
  11702. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11703. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11704. };
  11705. Engine.prototype.getStencilBuffer = function () {
  11706. return this._stencilState.stencilTest;
  11707. };
  11708. Engine.prototype.setStencilBuffer = function (enable) {
  11709. this._stencilState.stencilTest = enable;
  11710. };
  11711. Engine.prototype.getStencilMask = function () {
  11712. return this._stencilState.stencilMask;
  11713. };
  11714. Engine.prototype.setStencilMask = function (mask) {
  11715. this._stencilState.stencilMask = mask;
  11716. };
  11717. Engine.prototype.getStencilFunction = function () {
  11718. return this._stencilState.stencilFunc;
  11719. };
  11720. Engine.prototype.getStencilFunctionReference = function () {
  11721. return this._stencilState.stencilFuncRef;
  11722. };
  11723. Engine.prototype.getStencilFunctionMask = function () {
  11724. return this._stencilState.stencilFuncMask;
  11725. };
  11726. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11727. this._stencilState.stencilFunc = stencilFunc;
  11728. };
  11729. Engine.prototype.setStencilFunctionReference = function (reference) {
  11730. this._stencilState.stencilFuncRef = reference;
  11731. };
  11732. Engine.prototype.setStencilFunctionMask = function (mask) {
  11733. this._stencilState.stencilFuncMask = mask;
  11734. };
  11735. Engine.prototype.getStencilOperationFail = function () {
  11736. return this._stencilState.stencilOpStencilFail;
  11737. };
  11738. Engine.prototype.getStencilOperationDepthFail = function () {
  11739. return this._stencilState.stencilOpDepthFail;
  11740. };
  11741. Engine.prototype.getStencilOperationPass = function () {
  11742. return this._stencilState.stencilOpStencilDepthPass;
  11743. };
  11744. Engine.prototype.setStencilOperationFail = function (operation) {
  11745. this._stencilState.stencilOpStencilFail = operation;
  11746. };
  11747. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11748. this._stencilState.stencilOpDepthFail = operation;
  11749. };
  11750. Engine.prototype.setStencilOperationPass = function (operation) {
  11751. this._stencilState.stencilOpStencilDepthPass = operation;
  11752. };
  11753. Engine.prototype.setDitheringState = function (value) {
  11754. if (value) {
  11755. this._gl.enable(this._gl.DITHER);
  11756. }
  11757. else {
  11758. this._gl.disable(this._gl.DITHER);
  11759. }
  11760. };
  11761. Engine.prototype.setRasterizerState = function (value) {
  11762. if (value) {
  11763. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11764. }
  11765. else {
  11766. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11767. }
  11768. };
  11769. /**
  11770. * stop executing a render loop function and remove it from the execution array
  11771. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11772. */
  11773. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11774. if (!renderFunction) {
  11775. this._activeRenderLoops = [];
  11776. return;
  11777. }
  11778. var index = this._activeRenderLoops.indexOf(renderFunction);
  11779. if (index >= 0) {
  11780. this._activeRenderLoops.splice(index, 1);
  11781. }
  11782. };
  11783. Engine.prototype._renderLoop = function () {
  11784. if (!this._contextWasLost) {
  11785. var shouldRender = true;
  11786. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11787. shouldRender = false;
  11788. }
  11789. if (shouldRender) {
  11790. // Start new frame
  11791. this.beginFrame();
  11792. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11793. var renderFunction = this._activeRenderLoops[index];
  11794. renderFunction();
  11795. }
  11796. // Present
  11797. this.endFrame();
  11798. }
  11799. }
  11800. if (this._activeRenderLoops.length > 0) {
  11801. // Register new frame
  11802. var requester = null;
  11803. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11804. requester = this._vrDisplay;
  11805. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11806. }
  11807. else {
  11808. this._renderingQueueLaunched = false;
  11809. }
  11810. };
  11811. /**
  11812. * Register and execute a render loop. The engine can have more than one render function.
  11813. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11814. * @example
  11815. * engine.runRenderLoop(function () {
  11816. * scene.render()
  11817. * })
  11818. */
  11819. Engine.prototype.runRenderLoop = function (renderFunction) {
  11820. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11821. return;
  11822. }
  11823. this._activeRenderLoops.push(renderFunction);
  11824. if (!this._renderingQueueLaunched) {
  11825. this._renderingQueueLaunched = true;
  11826. this._bindedRenderFunction = this._renderLoop.bind(this);
  11827. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11828. }
  11829. };
  11830. /**
  11831. * Toggle full screen mode.
  11832. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11833. * @param {any} options - an options object to be sent to the requestFullscreen function
  11834. */
  11835. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11836. if (this.isFullscreen) {
  11837. BABYLON.Tools.ExitFullscreen();
  11838. }
  11839. else {
  11840. this._pointerLockRequested = requestPointerLock;
  11841. if (this._renderingCanvas) {
  11842. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11843. }
  11844. }
  11845. };
  11846. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11847. if (stencil === void 0) { stencil = false; }
  11848. this.applyStates();
  11849. var mode = 0;
  11850. if (backBuffer && color) {
  11851. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11852. mode |= this._gl.COLOR_BUFFER_BIT;
  11853. }
  11854. if (depth) {
  11855. this._gl.clearDepth(1.0);
  11856. mode |= this._gl.DEPTH_BUFFER_BIT;
  11857. }
  11858. if (stencil) {
  11859. this._gl.clearStencil(0);
  11860. mode |= this._gl.STENCIL_BUFFER_BIT;
  11861. }
  11862. this._gl.clear(mode);
  11863. };
  11864. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11865. var gl = this._gl;
  11866. // Save state
  11867. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11868. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11869. // Change state
  11870. gl.enable(gl.SCISSOR_TEST);
  11871. gl.scissor(x, y, width, height);
  11872. // Clear
  11873. this.clear(clearColor, true, true, true);
  11874. // Restore state
  11875. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11876. if (curScissor === true) {
  11877. gl.enable(gl.SCISSOR_TEST);
  11878. }
  11879. else {
  11880. gl.disable(gl.SCISSOR_TEST);
  11881. }
  11882. };
  11883. /**
  11884. * Set the WebGL's viewport
  11885. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11886. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11887. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11888. */
  11889. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11890. var width = requiredWidth || this.getRenderWidth();
  11891. var height = requiredHeight || this.getRenderHeight();
  11892. var x = viewport.x || 0;
  11893. var y = viewport.y || 0;
  11894. this._cachedViewport = viewport;
  11895. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11896. };
  11897. /**
  11898. * Directly set the WebGL Viewport
  11899. * The x, y, width & height are directly passed to the WebGL call
  11900. * @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.
  11901. */
  11902. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11903. var currentViewport = this._cachedViewport;
  11904. this._cachedViewport = null;
  11905. this._gl.viewport(x, y, width, height);
  11906. return currentViewport;
  11907. };
  11908. Engine.prototype.beginFrame = function () {
  11909. this.onBeginFrameObservable.notifyObservers(this);
  11910. this._measureFps();
  11911. };
  11912. Engine.prototype.endFrame = function () {
  11913. //force a flush in case we are using a bad OS.
  11914. if (this._badOS) {
  11915. this.flushFramebuffer();
  11916. }
  11917. //submit frame to the vr device, if enabled
  11918. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11919. // TODO: We should only submit the frame if we read frameData successfully.
  11920. this._vrDisplay.submitFrame();
  11921. }
  11922. this.onEndFrameObservable.notifyObservers(this);
  11923. };
  11924. /**
  11925. * resize the view according to the canvas' size.
  11926. * @example
  11927. * window.addEventListener("resize", function () {
  11928. * engine.resize();
  11929. * });
  11930. */
  11931. Engine.prototype.resize = function () {
  11932. // We're not resizing the size of the canvas while in VR mode & presenting
  11933. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11934. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11935. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11936. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11937. }
  11938. };
  11939. /**
  11940. * force a specific size of the canvas
  11941. * @param {number} width - the new canvas' width
  11942. * @param {number} height - the new canvas' height
  11943. */
  11944. Engine.prototype.setSize = function (width, height) {
  11945. if (!this._renderingCanvas) {
  11946. return;
  11947. }
  11948. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11949. return;
  11950. }
  11951. this._renderingCanvas.width = width;
  11952. this._renderingCanvas.height = height;
  11953. for (var index = 0; index < this.scenes.length; index++) {
  11954. var scene = this.scenes[index];
  11955. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11956. var cam = scene.cameras[camIndex];
  11957. cam._currentRenderId = 0;
  11958. }
  11959. }
  11960. if (this.onResizeObservable.hasObservers) {
  11961. this.onResizeObservable.notifyObservers(this);
  11962. }
  11963. };
  11964. // WebVR functions
  11965. Engine.prototype.isVRDevicePresent = function () {
  11966. return !!this._vrDisplay;
  11967. };
  11968. Engine.prototype.getVRDevice = function () {
  11969. return this._vrDisplay;
  11970. };
  11971. /**
  11972. * Initializes a webVR display and starts listening to display change events.
  11973. * The onVRDisplayChangedObservable will be notified upon these changes.
  11974. * @returns The onVRDisplayChangedObservable.
  11975. */
  11976. Engine.prototype.initWebVR = function () {
  11977. this.initWebVRAsync();
  11978. return this.onVRDisplayChangedObservable;
  11979. };
  11980. /**
  11981. * Initializes a webVR display and starts listening to display change events.
  11982. * The onVRDisplayChangedObservable will be notified upon these changes.
  11983. * @returns A promise containing a VRDisplay and if vr is supported.
  11984. */
  11985. Engine.prototype.initWebVRAsync = function () {
  11986. var _this = this;
  11987. var notifyObservers = function () {
  11988. var eventArgs = {
  11989. vrDisplay: _this._vrDisplay,
  11990. vrSupported: _this._vrSupported
  11991. };
  11992. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11993. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11994. };
  11995. if (!this._onVrDisplayConnect) {
  11996. this._onVrDisplayConnect = function (event) {
  11997. _this._vrDisplay = event.display;
  11998. notifyObservers();
  11999. };
  12000. this._onVrDisplayDisconnect = function () {
  12001. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12002. _this._vrDisplay = undefined;
  12003. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12004. notifyObservers();
  12005. };
  12006. this._onVrDisplayPresentChange = function () {
  12007. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12008. };
  12009. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12010. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12011. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12012. }
  12013. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12014. this._webVRInitPromise.then(notifyObservers);
  12015. return this._webVRInitPromise;
  12016. };
  12017. Engine.prototype.enableVR = function () {
  12018. var _this = this;
  12019. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12020. var onResolved = function () {
  12021. _this.onVRRequestPresentComplete.notifyObservers(true);
  12022. _this._onVRFullScreenTriggered();
  12023. };
  12024. var onRejected = function () {
  12025. _this.onVRRequestPresentComplete.notifyObservers(false);
  12026. };
  12027. this.onVRRequestPresentStart.notifyObservers(this);
  12028. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12029. }
  12030. };
  12031. Engine.prototype.disableVR = function () {
  12032. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12033. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12034. }
  12035. };
  12036. Engine.prototype._getVRDisplaysAsync = function () {
  12037. var _this = this;
  12038. return new Promise(function (res, rej) {
  12039. if (navigator.getVRDisplays) {
  12040. navigator.getVRDisplays().then(function (devices) {
  12041. _this._vrSupported = true;
  12042. // note that devices may actually be an empty array. This is fine;
  12043. // we expect this._vrDisplay to be undefined in this case.
  12044. _this._vrDisplay = devices[0];
  12045. res({
  12046. vrDisplay: _this._vrDisplay,
  12047. vrSupported: _this._vrSupported
  12048. });
  12049. });
  12050. }
  12051. else {
  12052. _this._vrDisplay = undefined;
  12053. _this._vrSupported = false;
  12054. res({
  12055. vrDisplay: _this._vrDisplay,
  12056. vrSupported: _this._vrSupported
  12057. });
  12058. }
  12059. });
  12060. };
  12061. /**
  12062. * Binds the frame buffer to the specified texture.
  12063. * @param texture The texture to render to or null for the default canvas
  12064. * @param faceIndex The face of the texture to render to in case of cube texture
  12065. * @param requiredWidth The width of the target to render to
  12066. * @param requiredHeight The height of the target to render to
  12067. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12068. * @param depthStencilTexture The depth stencil texture to use to render
  12069. */
  12070. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12071. if (this._currentRenderTarget) {
  12072. this.unBindFramebuffer(this._currentRenderTarget);
  12073. }
  12074. this._currentRenderTarget = texture;
  12075. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12076. var gl = this._gl;
  12077. if (texture.isCube) {
  12078. if (faceIndex === undefined) {
  12079. faceIndex = 0;
  12080. }
  12081. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12082. if (depthStencilTexture) {
  12083. if (depthStencilTexture._generateStencilBuffer) {
  12084. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12085. }
  12086. else {
  12087. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12088. }
  12089. }
  12090. }
  12091. if (this._cachedViewport && !forceFullscreenViewport) {
  12092. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12093. }
  12094. else {
  12095. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12096. }
  12097. this.wipeCaches();
  12098. };
  12099. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12100. if (this._currentFramebuffer !== framebuffer) {
  12101. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12102. this._currentFramebuffer = framebuffer;
  12103. }
  12104. };
  12105. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12106. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12107. this._currentRenderTarget = null;
  12108. // If MSAA, we need to bitblt back to main texture
  12109. var gl = this._gl;
  12110. if (texture._MSAAFramebuffer) {
  12111. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12112. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12113. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12114. }
  12115. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12116. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12117. gl.generateMipmap(gl.TEXTURE_2D);
  12118. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12119. }
  12120. if (onBeforeUnbind) {
  12121. if (texture._MSAAFramebuffer) {
  12122. // Bind the correct framebuffer
  12123. this.bindUnboundFramebuffer(texture._framebuffer);
  12124. }
  12125. onBeforeUnbind();
  12126. }
  12127. this.bindUnboundFramebuffer(null);
  12128. };
  12129. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12130. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12131. this._currentRenderTarget = null;
  12132. // If MSAA, we need to bitblt back to main texture
  12133. var gl = this._gl;
  12134. if (textures[0]._MSAAFramebuffer) {
  12135. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12136. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12137. var attachments = textures[0]._attachments;
  12138. if (!attachments) {
  12139. attachments = new Array(textures.length);
  12140. textures[0]._attachments = attachments;
  12141. }
  12142. for (var i = 0; i < textures.length; i++) {
  12143. var texture = textures[i];
  12144. for (var j = 0; j < attachments.length; j++) {
  12145. attachments[j] = gl.NONE;
  12146. }
  12147. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12148. gl.readBuffer(attachments[i]);
  12149. gl.drawBuffers(attachments);
  12150. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12151. }
  12152. for (var i = 0; i < attachments.length; i++) {
  12153. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12154. }
  12155. gl.drawBuffers(attachments);
  12156. }
  12157. for (var i = 0; i < textures.length; i++) {
  12158. var texture = textures[i];
  12159. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12160. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12161. gl.generateMipmap(gl.TEXTURE_2D);
  12162. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12163. }
  12164. }
  12165. if (onBeforeUnbind) {
  12166. if (textures[0]._MSAAFramebuffer) {
  12167. // Bind the correct framebuffer
  12168. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12169. }
  12170. onBeforeUnbind();
  12171. }
  12172. this.bindUnboundFramebuffer(null);
  12173. };
  12174. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12175. if (texture.generateMipMaps) {
  12176. var gl = this._gl;
  12177. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12178. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12179. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12180. }
  12181. };
  12182. Engine.prototype.flushFramebuffer = function () {
  12183. this._gl.flush();
  12184. };
  12185. Engine.prototype.restoreDefaultFramebuffer = function () {
  12186. if (this._currentRenderTarget) {
  12187. this.unBindFramebuffer(this._currentRenderTarget);
  12188. }
  12189. else {
  12190. this.bindUnboundFramebuffer(null);
  12191. }
  12192. if (this._cachedViewport) {
  12193. this.setViewport(this._cachedViewport);
  12194. }
  12195. this.wipeCaches();
  12196. };
  12197. // UBOs
  12198. Engine.prototype.createUniformBuffer = function (elements) {
  12199. var ubo = this._gl.createBuffer();
  12200. if (!ubo) {
  12201. throw new Error("Unable to create uniform buffer");
  12202. }
  12203. this.bindUniformBuffer(ubo);
  12204. if (elements instanceof Float32Array) {
  12205. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12206. }
  12207. else {
  12208. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12209. }
  12210. this.bindUniformBuffer(null);
  12211. ubo.references = 1;
  12212. return ubo;
  12213. };
  12214. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12215. var ubo = this._gl.createBuffer();
  12216. if (!ubo) {
  12217. throw new Error("Unable to create dynamic uniform buffer");
  12218. }
  12219. this.bindUniformBuffer(ubo);
  12220. if (elements instanceof Float32Array) {
  12221. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12222. }
  12223. else {
  12224. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12225. }
  12226. this.bindUniformBuffer(null);
  12227. ubo.references = 1;
  12228. return ubo;
  12229. };
  12230. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12231. this.bindUniformBuffer(uniformBuffer);
  12232. if (offset === undefined) {
  12233. offset = 0;
  12234. }
  12235. if (count === undefined) {
  12236. if (elements instanceof Float32Array) {
  12237. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12238. }
  12239. else {
  12240. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12241. }
  12242. }
  12243. else {
  12244. if (elements instanceof Float32Array) {
  12245. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12246. }
  12247. else {
  12248. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12249. }
  12250. }
  12251. this.bindUniformBuffer(null);
  12252. };
  12253. // VBOs
  12254. Engine.prototype._resetVertexBufferBinding = function () {
  12255. this.bindArrayBuffer(null);
  12256. this._cachedVertexBuffers = null;
  12257. };
  12258. Engine.prototype.createVertexBuffer = function (vertices) {
  12259. var vbo = this._gl.createBuffer();
  12260. if (!vbo) {
  12261. throw new Error("Unable to create vertex buffer");
  12262. }
  12263. this.bindArrayBuffer(vbo);
  12264. if (vertices instanceof Float32Array) {
  12265. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12266. }
  12267. else {
  12268. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12269. }
  12270. this._resetVertexBufferBinding();
  12271. vbo.references = 1;
  12272. return vbo;
  12273. };
  12274. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12275. var vbo = this._gl.createBuffer();
  12276. if (!vbo) {
  12277. throw new Error("Unable to create dynamic vertex buffer");
  12278. }
  12279. this.bindArrayBuffer(vbo);
  12280. if (vertices instanceof Float32Array) {
  12281. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12282. }
  12283. else {
  12284. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12285. }
  12286. this._resetVertexBufferBinding();
  12287. vbo.references = 1;
  12288. return vbo;
  12289. };
  12290. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12291. if (offset === void 0) { offset = 0; }
  12292. // Force cache update
  12293. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12294. this.bindIndexBuffer(indexBuffer);
  12295. var arrayBuffer;
  12296. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12297. arrayBuffer = indices;
  12298. }
  12299. else {
  12300. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12301. }
  12302. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12303. this._resetIndexBufferBinding();
  12304. };
  12305. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12306. this.bindArrayBuffer(vertexBuffer);
  12307. if (offset === undefined) {
  12308. offset = 0;
  12309. }
  12310. if (count === undefined) {
  12311. if (vertices instanceof Float32Array) {
  12312. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12313. }
  12314. else {
  12315. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12316. }
  12317. }
  12318. else {
  12319. if (vertices instanceof Float32Array) {
  12320. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12321. }
  12322. else {
  12323. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12324. }
  12325. }
  12326. this._resetVertexBufferBinding();
  12327. };
  12328. Engine.prototype._resetIndexBufferBinding = function () {
  12329. this.bindIndexBuffer(null);
  12330. this._cachedIndexBuffer = null;
  12331. };
  12332. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12333. var vbo = this._gl.createBuffer();
  12334. if (!vbo) {
  12335. throw new Error("Unable to create index buffer");
  12336. }
  12337. this.bindIndexBuffer(vbo);
  12338. // Check for 32 bits indices
  12339. var arrayBuffer;
  12340. var need32Bits = false;
  12341. if (indices instanceof Uint16Array) {
  12342. arrayBuffer = indices;
  12343. }
  12344. else {
  12345. //check 32 bit support
  12346. if (this._caps.uintIndices) {
  12347. if (indices instanceof Uint32Array) {
  12348. arrayBuffer = indices;
  12349. need32Bits = true;
  12350. }
  12351. else {
  12352. //number[] or Int32Array, check if 32 bit is necessary
  12353. for (var index = 0; index < indices.length; index++) {
  12354. if (indices[index] > 65535) {
  12355. need32Bits = true;
  12356. break;
  12357. }
  12358. }
  12359. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12360. }
  12361. }
  12362. else {
  12363. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12364. arrayBuffer = new Uint16Array(indices);
  12365. }
  12366. }
  12367. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12368. this._resetIndexBufferBinding();
  12369. vbo.references = 1;
  12370. vbo.is32Bits = need32Bits;
  12371. return vbo;
  12372. };
  12373. Engine.prototype.bindArrayBuffer = function (buffer) {
  12374. if (!this._vaoRecordInProgress) {
  12375. this._unbindVertexArrayObject();
  12376. }
  12377. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12378. };
  12379. Engine.prototype.bindUniformBuffer = function (buffer) {
  12380. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12381. };
  12382. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12383. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12384. };
  12385. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12386. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12387. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12388. };
  12389. ;
  12390. Engine.prototype.bindIndexBuffer = function (buffer) {
  12391. if (!this._vaoRecordInProgress) {
  12392. this._unbindVertexArrayObject();
  12393. }
  12394. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12395. };
  12396. Engine.prototype.bindBuffer = function (buffer, target) {
  12397. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12398. this._gl.bindBuffer(target, buffer);
  12399. this._currentBoundBuffer[target] = buffer;
  12400. }
  12401. };
  12402. Engine.prototype.updateArrayBuffer = function (data) {
  12403. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12404. };
  12405. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12406. var pointer = this._currentBufferPointers[indx];
  12407. var changed = false;
  12408. if (!pointer.active) {
  12409. changed = true;
  12410. pointer.active = true;
  12411. pointer.index = indx;
  12412. pointer.size = size;
  12413. pointer.type = type;
  12414. pointer.normalized = normalized;
  12415. pointer.stride = stride;
  12416. pointer.offset = offset;
  12417. pointer.buffer = buffer;
  12418. }
  12419. else {
  12420. if (pointer.buffer !== buffer) {
  12421. pointer.buffer = buffer;
  12422. changed = true;
  12423. }
  12424. if (pointer.size !== size) {
  12425. pointer.size = size;
  12426. changed = true;
  12427. }
  12428. if (pointer.type !== type) {
  12429. pointer.type = type;
  12430. changed = true;
  12431. }
  12432. if (pointer.normalized !== normalized) {
  12433. pointer.normalized = normalized;
  12434. changed = true;
  12435. }
  12436. if (pointer.stride !== stride) {
  12437. pointer.stride = stride;
  12438. changed = true;
  12439. }
  12440. if (pointer.offset !== offset) {
  12441. pointer.offset = offset;
  12442. changed = true;
  12443. }
  12444. }
  12445. if (changed || this._vaoRecordInProgress) {
  12446. this.bindArrayBuffer(buffer);
  12447. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12448. }
  12449. };
  12450. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12451. if (indexBuffer == null) {
  12452. return;
  12453. }
  12454. if (this._cachedIndexBuffer !== indexBuffer) {
  12455. this._cachedIndexBuffer = indexBuffer;
  12456. this.bindIndexBuffer(indexBuffer);
  12457. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12458. }
  12459. };
  12460. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12461. var attributes = effect.getAttributesNames();
  12462. if (!this._vaoRecordInProgress) {
  12463. this._unbindVertexArrayObject();
  12464. }
  12465. this.unbindAllAttributes();
  12466. for (var index = 0; index < attributes.length; index++) {
  12467. var order = effect.getAttributeLocation(index);
  12468. if (order >= 0) {
  12469. var vertexBuffer = vertexBuffers[attributes[index]];
  12470. if (!vertexBuffer) {
  12471. continue;
  12472. }
  12473. this._gl.enableVertexAttribArray(order);
  12474. if (!this._vaoRecordInProgress) {
  12475. this._vertexAttribArraysEnabled[order] = true;
  12476. }
  12477. var buffer = vertexBuffer.getBuffer();
  12478. if (buffer) {
  12479. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12480. if (vertexBuffer.getIsInstanced()) {
  12481. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12482. if (!this._vaoRecordInProgress) {
  12483. this._currentInstanceLocations.push(order);
  12484. this._currentInstanceBuffers.push(buffer);
  12485. }
  12486. }
  12487. }
  12488. }
  12489. }
  12490. };
  12491. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12492. var vao = this._gl.createVertexArray();
  12493. this._vaoRecordInProgress = true;
  12494. this._gl.bindVertexArray(vao);
  12495. this._mustWipeVertexAttributes = true;
  12496. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12497. this.bindIndexBuffer(indexBuffer);
  12498. this._vaoRecordInProgress = false;
  12499. this._gl.bindVertexArray(null);
  12500. return vao;
  12501. };
  12502. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12503. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12504. this._cachedVertexArrayObject = vertexArrayObject;
  12505. this._gl.bindVertexArray(vertexArrayObject);
  12506. this._cachedVertexBuffers = null;
  12507. this._cachedIndexBuffer = null;
  12508. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12509. this._mustWipeVertexAttributes = true;
  12510. }
  12511. };
  12512. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12513. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12514. this._cachedVertexBuffers = vertexBuffer;
  12515. this._cachedEffectForVertexBuffers = effect;
  12516. var attributesCount = effect.getAttributesCount();
  12517. this._unbindVertexArrayObject();
  12518. this.unbindAllAttributes();
  12519. var offset = 0;
  12520. for (var index = 0; index < attributesCount; index++) {
  12521. if (index < vertexDeclaration.length) {
  12522. var order = effect.getAttributeLocation(index);
  12523. if (order >= 0) {
  12524. this._gl.enableVertexAttribArray(order);
  12525. this._vertexAttribArraysEnabled[order] = true;
  12526. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12527. }
  12528. offset += vertexDeclaration[index] * 4;
  12529. }
  12530. }
  12531. }
  12532. this._bindIndexBufferWithCache(indexBuffer);
  12533. };
  12534. Engine.prototype._unbindVertexArrayObject = function () {
  12535. if (!this._cachedVertexArrayObject) {
  12536. return;
  12537. }
  12538. this._cachedVertexArrayObject = null;
  12539. this._gl.bindVertexArray(null);
  12540. };
  12541. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12542. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12543. this._cachedVertexBuffers = vertexBuffers;
  12544. this._cachedEffectForVertexBuffers = effect;
  12545. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12546. }
  12547. this._bindIndexBufferWithCache(indexBuffer);
  12548. };
  12549. Engine.prototype.unbindInstanceAttributes = function () {
  12550. var boundBuffer;
  12551. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12552. var instancesBuffer = this._currentInstanceBuffers[i];
  12553. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12554. boundBuffer = instancesBuffer;
  12555. this.bindArrayBuffer(instancesBuffer);
  12556. }
  12557. var offsetLocation = this._currentInstanceLocations[i];
  12558. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12559. }
  12560. this._currentInstanceBuffers.length = 0;
  12561. this._currentInstanceLocations.length = 0;
  12562. };
  12563. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12564. this._gl.deleteVertexArray(vao);
  12565. };
  12566. Engine.prototype._releaseBuffer = function (buffer) {
  12567. buffer.references--;
  12568. if (buffer.references === 0) {
  12569. this._gl.deleteBuffer(buffer);
  12570. return true;
  12571. }
  12572. return false;
  12573. };
  12574. Engine.prototype.createInstancesBuffer = function (capacity) {
  12575. var buffer = this._gl.createBuffer();
  12576. if (!buffer) {
  12577. throw new Error("Unable to create instance buffer");
  12578. }
  12579. buffer.capacity = capacity;
  12580. this.bindArrayBuffer(buffer);
  12581. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12582. return buffer;
  12583. };
  12584. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12585. this._gl.deleteBuffer(buffer);
  12586. };
  12587. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12588. this.bindArrayBuffer(instancesBuffer);
  12589. if (data) {
  12590. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12591. }
  12592. if (offsetLocations[0].index !== undefined) {
  12593. var stride = 0;
  12594. for (var i = 0; i < offsetLocations.length; i++) {
  12595. var ai = offsetLocations[i];
  12596. stride += ai.attributeSize * 4;
  12597. }
  12598. for (var i = 0; i < offsetLocations.length; i++) {
  12599. var ai = offsetLocations[i];
  12600. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12601. this._gl.enableVertexAttribArray(ai.index);
  12602. this._vertexAttribArraysEnabled[ai.index] = true;
  12603. }
  12604. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12605. this._gl.vertexAttribDivisor(ai.index, 1);
  12606. this._currentInstanceLocations.push(ai.index);
  12607. this._currentInstanceBuffers.push(instancesBuffer);
  12608. }
  12609. }
  12610. else {
  12611. for (var index = 0; index < 4; index++) {
  12612. var offsetLocation = offsetLocations[index];
  12613. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12614. this._gl.enableVertexAttribArray(offsetLocation);
  12615. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12616. }
  12617. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12618. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12619. this._currentInstanceLocations.push(offsetLocation);
  12620. this._currentInstanceBuffers.push(instancesBuffer);
  12621. }
  12622. }
  12623. };
  12624. Engine.prototype.applyStates = function () {
  12625. this._depthCullingState.apply(this._gl);
  12626. this._stencilState.apply(this._gl);
  12627. this._alphaState.apply(this._gl);
  12628. };
  12629. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12630. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12631. };
  12632. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12633. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12634. };
  12635. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12636. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12637. };
  12638. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12639. // Apply states
  12640. this.applyStates();
  12641. this._drawCalls.addCount(1, false);
  12642. // Render
  12643. var drawMode = this._drawMode(fillMode);
  12644. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12645. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12646. if (instancesCount) {
  12647. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12648. }
  12649. else {
  12650. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12651. }
  12652. };
  12653. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12654. // Apply states
  12655. this.applyStates();
  12656. this._drawCalls.addCount(1, false);
  12657. var drawMode = this._drawMode(fillMode);
  12658. if (instancesCount) {
  12659. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12660. }
  12661. else {
  12662. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12663. }
  12664. };
  12665. Engine.prototype._drawMode = function (fillMode) {
  12666. switch (fillMode) {
  12667. // Triangle views
  12668. case BABYLON.Material.TriangleFillMode:
  12669. return this._gl.TRIANGLES;
  12670. case BABYLON.Material.PointFillMode:
  12671. return this._gl.POINTS;
  12672. case BABYLON.Material.WireFrameFillMode:
  12673. return this._gl.LINES;
  12674. // Draw modes
  12675. case BABYLON.Material.PointListDrawMode:
  12676. return this._gl.POINTS;
  12677. case BABYLON.Material.LineListDrawMode:
  12678. return this._gl.LINES;
  12679. case BABYLON.Material.LineLoopDrawMode:
  12680. return this._gl.LINE_LOOP;
  12681. case BABYLON.Material.LineStripDrawMode:
  12682. return this._gl.LINE_STRIP;
  12683. case BABYLON.Material.TriangleStripDrawMode:
  12684. return this._gl.TRIANGLE_STRIP;
  12685. case BABYLON.Material.TriangleFanDrawMode:
  12686. return this._gl.TRIANGLE_FAN;
  12687. default:
  12688. return this._gl.TRIANGLES;
  12689. }
  12690. };
  12691. // Shaders
  12692. Engine.prototype._releaseEffect = function (effect) {
  12693. if (this._compiledEffects[effect._key]) {
  12694. delete this._compiledEffects[effect._key];
  12695. this._deleteProgram(effect.getProgram());
  12696. }
  12697. };
  12698. Engine.prototype._deleteProgram = function (program) {
  12699. if (program) {
  12700. program.__SPECTOR_rebuildProgram = null;
  12701. if (program.transformFeedback) {
  12702. this.deleteTransformFeedback(program.transformFeedback);
  12703. program.transformFeedback = null;
  12704. }
  12705. this._gl.deleteProgram(program);
  12706. }
  12707. };
  12708. /**
  12709. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12710. * @param samplers An array of string used to represent textures
  12711. */
  12712. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12713. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12714. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12715. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12716. if (this._compiledEffects[name]) {
  12717. var compiledEffect = this._compiledEffects[name];
  12718. if (onCompiled && compiledEffect.isReady()) {
  12719. onCompiled(compiledEffect);
  12720. }
  12721. return compiledEffect;
  12722. }
  12723. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12724. effect._key = name;
  12725. this._compiledEffects[name] = effect;
  12726. return effect;
  12727. };
  12728. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12729. if (uniformsNames === void 0) { uniformsNames = []; }
  12730. if (samplers === void 0) { samplers = []; }
  12731. if (defines === void 0) { defines = ""; }
  12732. return this.createEffect({
  12733. vertex: "particles",
  12734. fragmentElement: fragmentName
  12735. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12736. };
  12737. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12738. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12739. context = context || this._gl;
  12740. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12741. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12742. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12743. };
  12744. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12745. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12746. context = context || this._gl;
  12747. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12748. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12749. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12750. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12751. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12752. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12753. return program;
  12754. };
  12755. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12756. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12757. var shaderProgram = context.createProgram();
  12758. if (!shaderProgram) {
  12759. throw new Error("Unable to create program");
  12760. }
  12761. context.attachShader(shaderProgram, vertexShader);
  12762. context.attachShader(shaderProgram, fragmentShader);
  12763. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12764. var transformFeedback = this.createTransformFeedback();
  12765. this.bindTransformFeedback(transformFeedback);
  12766. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12767. shaderProgram.transformFeedback = transformFeedback;
  12768. }
  12769. context.linkProgram(shaderProgram);
  12770. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12771. this.bindTransformFeedback(null);
  12772. }
  12773. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12774. if (!linked) {
  12775. context.validateProgram(shaderProgram);
  12776. var error = context.getProgramInfoLog(shaderProgram);
  12777. if (error) {
  12778. throw new Error(error);
  12779. }
  12780. }
  12781. context.deleteShader(vertexShader);
  12782. context.deleteShader(fragmentShader);
  12783. return shaderProgram;
  12784. };
  12785. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12786. var results = new Array();
  12787. for (var index = 0; index < uniformsNames.length; index++) {
  12788. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12789. }
  12790. return results;
  12791. };
  12792. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12793. var results = [];
  12794. for (var index = 0; index < attributesNames.length; index++) {
  12795. try {
  12796. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12797. }
  12798. catch (e) {
  12799. results.push(-1);
  12800. }
  12801. }
  12802. return results;
  12803. };
  12804. Engine.prototype.enableEffect = function (effect) {
  12805. if (!effect) {
  12806. return;
  12807. }
  12808. // Use program
  12809. this.bindSamplers(effect);
  12810. this._currentEffect = effect;
  12811. if (effect.onBind) {
  12812. effect.onBind(effect);
  12813. }
  12814. effect.onBindObservable.notifyObservers(effect);
  12815. };
  12816. Engine.prototype.setIntArray = function (uniform, array) {
  12817. if (!uniform)
  12818. return;
  12819. this._gl.uniform1iv(uniform, array);
  12820. };
  12821. Engine.prototype.setIntArray2 = function (uniform, array) {
  12822. if (!uniform || array.length % 2 !== 0)
  12823. return;
  12824. this._gl.uniform2iv(uniform, array);
  12825. };
  12826. Engine.prototype.setIntArray3 = function (uniform, array) {
  12827. if (!uniform || array.length % 3 !== 0)
  12828. return;
  12829. this._gl.uniform3iv(uniform, array);
  12830. };
  12831. Engine.prototype.setIntArray4 = function (uniform, array) {
  12832. if (!uniform || array.length % 4 !== 0)
  12833. return;
  12834. this._gl.uniform4iv(uniform, array);
  12835. };
  12836. Engine.prototype.setFloatArray = function (uniform, array) {
  12837. if (!uniform)
  12838. return;
  12839. this._gl.uniform1fv(uniform, array);
  12840. };
  12841. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12842. if (!uniform || array.length % 2 !== 0)
  12843. return;
  12844. this._gl.uniform2fv(uniform, array);
  12845. };
  12846. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12847. if (!uniform || array.length % 3 !== 0)
  12848. return;
  12849. this._gl.uniform3fv(uniform, array);
  12850. };
  12851. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12852. if (!uniform || array.length % 4 !== 0)
  12853. return;
  12854. this._gl.uniform4fv(uniform, array);
  12855. };
  12856. Engine.prototype.setArray = function (uniform, array) {
  12857. if (!uniform)
  12858. return;
  12859. this._gl.uniform1fv(uniform, array);
  12860. };
  12861. Engine.prototype.setArray2 = function (uniform, array) {
  12862. if (!uniform || array.length % 2 !== 0)
  12863. return;
  12864. this._gl.uniform2fv(uniform, array);
  12865. };
  12866. Engine.prototype.setArray3 = function (uniform, array) {
  12867. if (!uniform || array.length % 3 !== 0)
  12868. return;
  12869. this._gl.uniform3fv(uniform, array);
  12870. };
  12871. Engine.prototype.setArray4 = function (uniform, array) {
  12872. if (!uniform || array.length % 4 !== 0)
  12873. return;
  12874. this._gl.uniform4fv(uniform, array);
  12875. };
  12876. Engine.prototype.setMatrices = function (uniform, matrices) {
  12877. if (!uniform)
  12878. return;
  12879. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12880. };
  12881. Engine.prototype.setMatrix = function (uniform, matrix) {
  12882. if (!uniform)
  12883. return;
  12884. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12885. };
  12886. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12887. if (!uniform)
  12888. return;
  12889. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12890. };
  12891. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12892. if (!uniform)
  12893. return;
  12894. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12895. };
  12896. Engine.prototype.setInt = function (uniform, value) {
  12897. if (!uniform)
  12898. return;
  12899. this._gl.uniform1i(uniform, value);
  12900. };
  12901. Engine.prototype.setFloat = function (uniform, value) {
  12902. if (!uniform)
  12903. return;
  12904. this._gl.uniform1f(uniform, value);
  12905. };
  12906. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12907. if (!uniform)
  12908. return;
  12909. this._gl.uniform2f(uniform, x, y);
  12910. };
  12911. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12912. if (!uniform)
  12913. return;
  12914. this._gl.uniform3f(uniform, x, y, z);
  12915. };
  12916. Engine.prototype.setBool = function (uniform, bool) {
  12917. if (!uniform)
  12918. return;
  12919. this._gl.uniform1i(uniform, bool);
  12920. };
  12921. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12922. if (!uniform)
  12923. return;
  12924. this._gl.uniform4f(uniform, x, y, z, w);
  12925. };
  12926. Engine.prototype.setColor3 = function (uniform, color3) {
  12927. if (!uniform)
  12928. return;
  12929. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12930. };
  12931. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12932. if (!uniform)
  12933. return;
  12934. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12935. };
  12936. /**
  12937. * Sets a Color4 on a uniform variable
  12938. * @param uniform defines the uniform location
  12939. * @param color4 defines the value to be set
  12940. */
  12941. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12942. if (!uniform)
  12943. return;
  12944. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12945. };
  12946. // States
  12947. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12948. if (zOffset === void 0) { zOffset = 0; }
  12949. if (reverseSide === void 0) { reverseSide = false; }
  12950. // Culling
  12951. if (this._depthCullingState.cull !== culling || force) {
  12952. this._depthCullingState.cull = culling;
  12953. }
  12954. // Cull face
  12955. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12956. if (this._depthCullingState.cullFace !== cullFace || force) {
  12957. this._depthCullingState.cullFace = cullFace;
  12958. }
  12959. // Z offset
  12960. this.setZOffset(zOffset);
  12961. // Front face
  12962. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12963. if (this._depthCullingState.frontFace !== frontFace || force) {
  12964. this._depthCullingState.frontFace = frontFace;
  12965. }
  12966. };
  12967. Engine.prototype.setZOffset = function (value) {
  12968. this._depthCullingState.zOffset = value;
  12969. };
  12970. Engine.prototype.getZOffset = function () {
  12971. return this._depthCullingState.zOffset;
  12972. };
  12973. Engine.prototype.setDepthBuffer = function (enable) {
  12974. this._depthCullingState.depthTest = enable;
  12975. };
  12976. Engine.prototype.getDepthWrite = function () {
  12977. return this._depthCullingState.depthMask;
  12978. };
  12979. Engine.prototype.setDepthWrite = function (enable) {
  12980. this._depthCullingState.depthMask = enable;
  12981. };
  12982. Engine.prototype.setColorWrite = function (enable) {
  12983. this._gl.colorMask(enable, enable, enable, enable);
  12984. this._colorWrite = enable;
  12985. };
  12986. Engine.prototype.getColorWrite = function () {
  12987. return this._colorWrite;
  12988. };
  12989. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12990. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12991. };
  12992. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12993. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12994. if (this._alphaMode === mode) {
  12995. return;
  12996. }
  12997. switch (mode) {
  12998. case Engine.ALPHA_DISABLE:
  12999. this._alphaState.alphaBlend = false;
  13000. break;
  13001. case Engine.ALPHA_PREMULTIPLIED:
  13002. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13003. this._alphaState.alphaBlend = true;
  13004. break;
  13005. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  13006. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13007. this._alphaState.alphaBlend = true;
  13008. break;
  13009. case Engine.ALPHA_COMBINE:
  13010. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13011. this._alphaState.alphaBlend = true;
  13012. break;
  13013. case Engine.ALPHA_ONEONE:
  13014. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13015. this._alphaState.alphaBlend = true;
  13016. break;
  13017. case Engine.ALPHA_ADD:
  13018. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13019. this._alphaState.alphaBlend = true;
  13020. break;
  13021. case Engine.ALPHA_SUBTRACT:
  13022. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13023. this._alphaState.alphaBlend = true;
  13024. break;
  13025. case Engine.ALPHA_MULTIPLY:
  13026. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  13027. this._alphaState.alphaBlend = true;
  13028. break;
  13029. case Engine.ALPHA_MAXIMIZED:
  13030. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13031. this._alphaState.alphaBlend = true;
  13032. break;
  13033. case Engine.ALPHA_INTERPOLATE:
  13034. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  13035. this._alphaState.alphaBlend = true;
  13036. break;
  13037. case Engine.ALPHA_SCREENMODE:
  13038. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13039. this._alphaState.alphaBlend = true;
  13040. break;
  13041. }
  13042. if (!noDepthWriteChange) {
  13043. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13044. }
  13045. this._alphaMode = mode;
  13046. };
  13047. Engine.prototype.getAlphaMode = function () {
  13048. return this._alphaMode;
  13049. };
  13050. // Textures
  13051. Engine.prototype.wipeCaches = function (bruteForce) {
  13052. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13053. return;
  13054. }
  13055. this._currentEffect = null;
  13056. // 6/8/2017: deltakosh: Should not be required anymore.
  13057. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13058. if (bruteForce) {
  13059. this.resetTextureCache();
  13060. this._currentProgram = null;
  13061. this._stencilState.reset();
  13062. this._depthCullingState.reset();
  13063. this.setDepthFunctionToLessOrEqual();
  13064. this._alphaState.reset();
  13065. }
  13066. this._resetVertexBufferBinding();
  13067. this._cachedIndexBuffer = null;
  13068. this._cachedEffectForVertexBuffers = null;
  13069. this._unbindVertexArrayObject();
  13070. this.bindIndexBuffer(null);
  13071. };
  13072. /**
  13073. * Set the compressed texture format to use, based on the formats you have, and the formats
  13074. * supported by the hardware / browser.
  13075. *
  13076. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13077. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13078. * to API arguments needed to compressed textures. This puts the burden on the container
  13079. * generator to house the arcane code for determining these for current & future formats.
  13080. *
  13081. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13082. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13083. *
  13084. * Note: The result of this call is not taken into account when a texture is base64.
  13085. *
  13086. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13087. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13088. *
  13089. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13090. * @returns The extension selected.
  13091. */
  13092. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13093. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13094. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13095. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13096. return this._textureFormatInUse = this._texturesSupported[i];
  13097. }
  13098. }
  13099. }
  13100. // actively set format to nothing, to allow this to be called more than once
  13101. // and possibly fail the 2nd time
  13102. this._textureFormatInUse = null;
  13103. return null;
  13104. };
  13105. Engine.prototype._createTexture = function () {
  13106. var texture = this._gl.createTexture();
  13107. if (!texture) {
  13108. throw new Error("Unable to create texture");
  13109. }
  13110. return texture;
  13111. };
  13112. /**
  13113. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13114. * @param {string} urlArg- This contains one of the following:
  13115. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13116. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13117. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13118. *
  13119. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13120. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13121. * @param {Scene} scene- Needed for loading to the correct scene.
  13122. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13123. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13124. * @param {callback} onError- Optional callback to be called upon failure.
  13125. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13126. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13127. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13128. *
  13129. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13130. */
  13131. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13132. var _this = this;
  13133. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13134. if (onLoad === void 0) { onLoad = null; }
  13135. if (onError === void 0) { onError = null; }
  13136. if (buffer === void 0) { buffer = null; }
  13137. if (fallBack === void 0) { fallBack = null; }
  13138. if (format === void 0) { format = null; }
  13139. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13140. var fromData = url.substr(0, 5) === "data:";
  13141. var fromBlob = url.substr(0, 5) === "blob:";
  13142. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13143. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13144. // establish the file extension, if possible
  13145. var lastDot = url.lastIndexOf('.');
  13146. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13147. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13148. var isTGA = (extension.indexOf(".tga") === 0);
  13149. // determine if a ktx file should be substituted
  13150. var isKTX = false;
  13151. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13152. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13153. isKTX = true;
  13154. }
  13155. if (scene) {
  13156. scene._addPendingData(texture);
  13157. }
  13158. texture.url = url;
  13159. texture.generateMipMaps = !noMipmap;
  13160. texture.samplingMode = samplingMode;
  13161. texture.invertY = invertY;
  13162. if (!this._doNotHandleContextLost) {
  13163. // Keep a link to the buffer only if we plan to handle context lost
  13164. texture._buffer = buffer;
  13165. }
  13166. var onLoadObserver = null;
  13167. if (onLoad && !fallBack) {
  13168. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13169. }
  13170. if (!fallBack)
  13171. this._internalTexturesCache.push(texture);
  13172. var onerror = function (message, exception) {
  13173. if (scene) {
  13174. scene._removePendingData(texture);
  13175. }
  13176. if (onLoadObserver) {
  13177. texture.onLoadedObservable.remove(onLoadObserver);
  13178. }
  13179. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13180. if (isKTX) {
  13181. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13182. }
  13183. else if (BABYLON.Tools.UseFallbackTexture) {
  13184. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13185. }
  13186. if (onError) {
  13187. onError(message || "Unknown error", exception);
  13188. }
  13189. };
  13190. var callback = null;
  13191. // processing for non-image formats
  13192. if (isKTX || isTGA || isDDS) {
  13193. if (isKTX) {
  13194. callback = function (data) {
  13195. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13196. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13197. ktx.uploadLevels(_this._gl, !noMipmap);
  13198. return false;
  13199. }, samplingMode);
  13200. };
  13201. }
  13202. else if (isTGA) {
  13203. callback = function (arrayBuffer) {
  13204. var data = new Uint8Array(arrayBuffer);
  13205. var header = BABYLON.TGATools.GetTGAHeader(data);
  13206. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13207. BABYLON.TGATools.UploadContent(_this._gl, data);
  13208. return false;
  13209. }, samplingMode);
  13210. };
  13211. }
  13212. else if (isDDS) {
  13213. callback = function (data) {
  13214. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13215. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13216. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13217. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13218. return false;
  13219. }, samplingMode);
  13220. };
  13221. }
  13222. if (!buffer) {
  13223. this._loadFile(url, function (data) {
  13224. if (callback) {
  13225. callback(data);
  13226. }
  13227. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13228. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13229. });
  13230. }
  13231. else {
  13232. if (callback) {
  13233. callback(buffer);
  13234. }
  13235. }
  13236. // image format processing
  13237. }
  13238. else {
  13239. var onload = function (img) {
  13240. if (fromBlob && !_this._doNotHandleContextLost) {
  13241. // We need to store the image if we need to rebuild the texture
  13242. // in case of a webgl context lost
  13243. texture._buffer = img;
  13244. }
  13245. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13246. var gl = _this._gl;
  13247. var isPot = (img.width === potWidth && img.height === potHeight);
  13248. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13249. if (isPot) {
  13250. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13251. return false;
  13252. }
  13253. // Using shaders to rescale because canvas.drawImage is lossy
  13254. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13255. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13256. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13257. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13258. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13259. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13260. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13261. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13262. _this._releaseTexture(source);
  13263. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13264. continuationCallback();
  13265. });
  13266. return true;
  13267. }, samplingMode);
  13268. };
  13269. if (!fromData || isBase64)
  13270. if (buffer instanceof HTMLImageElement) {
  13271. onload(buffer);
  13272. }
  13273. else {
  13274. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13275. }
  13276. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13277. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13278. else
  13279. onload(buffer);
  13280. }
  13281. return texture;
  13282. };
  13283. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13284. var _this = this;
  13285. var rtt = this.createRenderTargetTexture({
  13286. width: destination.width,
  13287. height: destination.height,
  13288. }, {
  13289. generateMipMaps: false,
  13290. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13291. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13292. generateDepthBuffer: false,
  13293. generateStencilBuffer: false
  13294. });
  13295. if (!this._rescalePostProcess) {
  13296. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13297. }
  13298. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13299. _this._rescalePostProcess.onApply = function (effect) {
  13300. effect._bindTexture("textureSampler", source);
  13301. };
  13302. var hostingScene = scene;
  13303. if (!hostingScene) {
  13304. hostingScene = _this.scenes[_this.scenes.length - 1];
  13305. }
  13306. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13307. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13308. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13309. _this.unBindFramebuffer(rtt);
  13310. _this._releaseTexture(rtt);
  13311. if (onComplete) {
  13312. onComplete();
  13313. }
  13314. });
  13315. };
  13316. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13317. if (compression === void 0) { compression = null; }
  13318. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13319. if (!texture) {
  13320. return;
  13321. }
  13322. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13323. var internalFormat = this._getInternalFormat(format);
  13324. var textureType = this._getWebGLTextureType(type);
  13325. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13326. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13327. if (!this._doNotHandleContextLost) {
  13328. texture._bufferView = data;
  13329. texture.format = format;
  13330. texture.type = type;
  13331. texture.invertY = invertY;
  13332. texture._compression = compression;
  13333. }
  13334. if (texture.width % 4 !== 0) {
  13335. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13336. }
  13337. if (compression && data) {
  13338. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13339. }
  13340. else {
  13341. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13342. }
  13343. if (texture.generateMipMaps) {
  13344. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13345. }
  13346. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13347. // this.resetTextureCache();
  13348. texture.isReady = true;
  13349. };
  13350. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13351. if (compression === void 0) { compression = null; }
  13352. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13353. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13354. texture.baseWidth = width;
  13355. texture.baseHeight = height;
  13356. texture.width = width;
  13357. texture.height = height;
  13358. texture.format = format;
  13359. texture.generateMipMaps = generateMipMaps;
  13360. texture.samplingMode = samplingMode;
  13361. texture.invertY = invertY;
  13362. texture._compression = compression;
  13363. texture.type = type;
  13364. if (!this._doNotHandleContextLost) {
  13365. texture._bufferView = data;
  13366. }
  13367. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13368. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13369. // Filters
  13370. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13371. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13372. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13373. if (generateMipMaps) {
  13374. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13375. }
  13376. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13377. this._internalTexturesCache.push(texture);
  13378. return texture;
  13379. };
  13380. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13381. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13382. texture.baseWidth = width;
  13383. texture.baseHeight = height;
  13384. if (generateMipMaps) {
  13385. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13386. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13387. }
  13388. // this.resetTextureCache();
  13389. texture.width = width;
  13390. texture.height = height;
  13391. texture.isReady = false;
  13392. texture.generateMipMaps = generateMipMaps;
  13393. texture.samplingMode = samplingMode;
  13394. this.updateTextureSamplingMode(samplingMode, texture);
  13395. this._internalTexturesCache.push(texture);
  13396. return texture;
  13397. };
  13398. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13399. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13400. if (texture.isCube) {
  13401. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13402. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13403. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13404. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13405. }
  13406. else if (texture.is3D) {
  13407. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13408. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13409. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13410. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13411. }
  13412. else {
  13413. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13414. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13415. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13416. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13417. }
  13418. texture.samplingMode = samplingMode;
  13419. };
  13420. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13421. if (premulAlpha === void 0) { premulAlpha = false; }
  13422. if (!texture) {
  13423. return;
  13424. }
  13425. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13426. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13427. if (premulAlpha) {
  13428. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13429. }
  13430. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13431. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13432. if (texture.generateMipMaps) {
  13433. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13434. }
  13435. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13436. if (premulAlpha) {
  13437. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13438. }
  13439. texture.isReady = true;
  13440. };
  13441. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13442. if (!texture || texture._isDisabled) {
  13443. return;
  13444. }
  13445. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13446. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13447. try {
  13448. // Testing video texture support
  13449. if (this._videoTextureSupported === undefined) {
  13450. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13451. if (this._gl.getError() !== 0) {
  13452. this._videoTextureSupported = false;
  13453. }
  13454. else {
  13455. this._videoTextureSupported = true;
  13456. }
  13457. }
  13458. // Copy video through the current working canvas if video texture is not supported
  13459. if (!this._videoTextureSupported) {
  13460. if (!texture._workingCanvas) {
  13461. texture._workingCanvas = document.createElement("canvas");
  13462. var context = texture._workingCanvas.getContext("2d");
  13463. if (!context) {
  13464. throw new Error("Unable to get 2d context");
  13465. }
  13466. texture._workingContext = context;
  13467. texture._workingCanvas.width = texture.width;
  13468. texture._workingCanvas.height = texture.height;
  13469. }
  13470. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13471. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13472. }
  13473. else {
  13474. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13475. }
  13476. if (texture.generateMipMaps) {
  13477. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13478. }
  13479. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13480. // this.resetTextureCache();
  13481. texture.isReady = true;
  13482. }
  13483. catch (ex) {
  13484. // Something unexpected
  13485. // Let's disable the texture
  13486. texture._isDisabled = true;
  13487. }
  13488. };
  13489. /**
  13490. * Updates a depth texture Comparison Mode and Function.
  13491. * If the comparison Function is equal to 0, the mode will be set to none.
  13492. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13493. * @param texture The texture to set the comparison function for
  13494. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13495. */
  13496. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13497. if (this.webGLVersion === 1) {
  13498. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13499. return;
  13500. }
  13501. var gl = this._gl;
  13502. if (texture.isCube) {
  13503. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13504. if (comparisonFunction === 0) {
  13505. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13506. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13507. }
  13508. else {
  13509. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13510. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13511. }
  13512. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13513. }
  13514. else {
  13515. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13516. if (comparisonFunction === 0) {
  13517. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13518. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13519. }
  13520. else {
  13521. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13522. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13523. }
  13524. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13525. }
  13526. texture._comparisonFunction = comparisonFunction;
  13527. };
  13528. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13529. var width = size.width || size;
  13530. var height = size.height || size;
  13531. internalTexture.baseWidth = width;
  13532. internalTexture.baseHeight = height;
  13533. internalTexture.width = width;
  13534. internalTexture.height = height;
  13535. internalTexture.isReady = true;
  13536. internalTexture.samples = 1;
  13537. internalTexture.generateMipMaps = false;
  13538. internalTexture._generateDepthBuffer = true;
  13539. internalTexture._generateStencilBuffer = generateStencil;
  13540. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13541. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13542. internalTexture._comparisonFunction = comparisonFunction;
  13543. var gl = this._gl;
  13544. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13545. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13546. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13547. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13548. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13549. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13550. if (comparisonFunction === 0) {
  13551. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13552. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13553. }
  13554. else {
  13555. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13556. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13557. }
  13558. };
  13559. /**
  13560. * Creates a depth stencil texture.
  13561. * This is only available in WebGL 2 or with the depth texture extension available.
  13562. * @param size The size of face edge in the texture.
  13563. * @param options The options defining the texture.
  13564. * @returns The texture
  13565. */
  13566. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13567. if (options.isCube) {
  13568. var width = size.width || size;
  13569. return this._createDepthStencilCubeTexture(width, options);
  13570. }
  13571. else {
  13572. return this._createDepthStencilTexture(size, options);
  13573. }
  13574. };
  13575. /**
  13576. * Creates a depth stencil texture.
  13577. * This is only available in WebGL 2 or with the depth texture extension available.
  13578. * @param size The size of face edge in the texture.
  13579. * @param options The options defining the texture.
  13580. * @returns The texture
  13581. */
  13582. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13583. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13584. if (!this._caps.depthTextureExtension) {
  13585. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13586. return internalTexture;
  13587. }
  13588. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13589. var gl = this._gl;
  13590. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13591. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13592. if (this.webGLVersion > 1) {
  13593. if (internalOptions.generateStencil) {
  13594. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13595. }
  13596. else {
  13597. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13598. }
  13599. }
  13600. else {
  13601. if (internalOptions.generateStencil) {
  13602. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13603. }
  13604. else {
  13605. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13606. }
  13607. }
  13608. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13609. return internalTexture;
  13610. };
  13611. /**
  13612. * Creates a depth stencil cube texture.
  13613. * This is only available in WebGL 2.
  13614. * @param size The size of face edge in the cube texture.
  13615. * @param options The options defining the cube texture.
  13616. * @returns The cube texture
  13617. */
  13618. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13619. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13620. internalTexture.isCube = true;
  13621. if (this.webGLVersion === 1) {
  13622. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13623. return internalTexture;
  13624. }
  13625. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13626. var gl = this._gl;
  13627. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13628. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13629. // Create the depth/stencil buffer
  13630. for (var face = 0; face < 6; face++) {
  13631. if (internalOptions.generateStencil) {
  13632. 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);
  13633. }
  13634. else {
  13635. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13636. }
  13637. }
  13638. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13639. return internalTexture;
  13640. };
  13641. /**
  13642. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13643. * @param renderTarget The render target to set the frame buffer for
  13644. */
  13645. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13646. // Create the framebuffer
  13647. var internalTexture = renderTarget.getInternalTexture();
  13648. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13649. return;
  13650. }
  13651. var gl = this._gl;
  13652. var depthStencilTexture = renderTarget.depthStencilTexture;
  13653. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13654. if (depthStencilTexture.isCube) {
  13655. if (depthStencilTexture._generateStencilBuffer) {
  13656. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13657. }
  13658. else {
  13659. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13660. }
  13661. }
  13662. else {
  13663. if (depthStencilTexture._generateStencilBuffer) {
  13664. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13665. }
  13666. else {
  13667. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13668. }
  13669. }
  13670. this.bindUnboundFramebuffer(null);
  13671. };
  13672. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13673. var fullOptions = new RenderTargetCreationOptions();
  13674. if (options !== undefined && typeof options === "object") {
  13675. fullOptions.generateMipMaps = options.generateMipMaps;
  13676. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13677. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13678. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13679. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13680. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13681. }
  13682. else {
  13683. fullOptions.generateMipMaps = options;
  13684. fullOptions.generateDepthBuffer = true;
  13685. fullOptions.generateStencilBuffer = false;
  13686. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13687. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13688. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13689. }
  13690. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13691. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13692. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13693. }
  13694. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13695. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13696. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13697. }
  13698. var gl = this._gl;
  13699. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13700. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13701. var width = size.width || size;
  13702. var height = size.height || size;
  13703. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13704. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13705. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13706. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13707. }
  13708. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13709. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13710. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13711. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13712. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13713. // Create the framebuffer
  13714. var framebuffer = gl.createFramebuffer();
  13715. this.bindUnboundFramebuffer(framebuffer);
  13716. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13717. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13718. if (fullOptions.generateMipMaps) {
  13719. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13720. }
  13721. // Unbind
  13722. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13723. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13724. this.bindUnboundFramebuffer(null);
  13725. texture._framebuffer = framebuffer;
  13726. texture.baseWidth = width;
  13727. texture.baseHeight = height;
  13728. texture.width = width;
  13729. texture.height = height;
  13730. texture.isReady = true;
  13731. texture.samples = 1;
  13732. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13733. texture.samplingMode = fullOptions.samplingMode;
  13734. texture.type = fullOptions.type;
  13735. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13736. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13737. // this.resetTextureCache();
  13738. this._internalTexturesCache.push(texture);
  13739. return texture;
  13740. };
  13741. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13742. var generateMipMaps = false;
  13743. var generateDepthBuffer = true;
  13744. var generateStencilBuffer = false;
  13745. var generateDepthTexture = false;
  13746. var textureCount = 1;
  13747. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13748. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13749. var types = [], samplingModes = [];
  13750. if (options !== undefined) {
  13751. generateMipMaps = options.generateMipMaps;
  13752. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13753. generateStencilBuffer = options.generateStencilBuffer;
  13754. generateDepthTexture = options.generateDepthTexture;
  13755. textureCount = options.textureCount || 1;
  13756. if (options.types) {
  13757. types = options.types;
  13758. }
  13759. if (options.samplingModes) {
  13760. samplingModes = options.samplingModes;
  13761. }
  13762. }
  13763. var gl = this._gl;
  13764. // Create the framebuffer
  13765. var framebuffer = gl.createFramebuffer();
  13766. this.bindUnboundFramebuffer(framebuffer);
  13767. var width = size.width || size;
  13768. var height = size.height || size;
  13769. var textures = [];
  13770. var attachments = [];
  13771. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13772. for (var i = 0; i < textureCount; i++) {
  13773. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13774. var type = types[i] || defaultType;
  13775. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13776. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13777. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13778. }
  13779. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13780. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13781. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13782. }
  13783. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13784. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13785. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13786. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13787. }
  13788. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13789. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13790. textures.push(texture);
  13791. attachments.push(attachment);
  13792. gl.activeTexture(gl["TEXTURE" + i]);
  13793. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13794. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13795. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13796. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13797. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13798. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13799. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13800. if (generateMipMaps) {
  13801. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13802. }
  13803. // Unbind
  13804. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13805. texture._framebuffer = framebuffer;
  13806. texture._depthStencilBuffer = depthStencilBuffer;
  13807. texture.baseWidth = width;
  13808. texture.baseHeight = height;
  13809. texture.width = width;
  13810. texture.height = height;
  13811. texture.isReady = true;
  13812. texture.samples = 1;
  13813. texture.generateMipMaps = generateMipMaps;
  13814. texture.samplingMode = samplingMode;
  13815. texture.type = type;
  13816. texture._generateDepthBuffer = generateDepthBuffer;
  13817. texture._generateStencilBuffer = generateStencilBuffer;
  13818. texture._attachments = attachments;
  13819. this._internalTexturesCache.push(texture);
  13820. }
  13821. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13822. // Depth texture
  13823. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13824. gl.activeTexture(gl.TEXTURE0);
  13825. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13826. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13827. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13828. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13829. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13830. 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);
  13831. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13832. depthTexture._framebuffer = framebuffer;
  13833. depthTexture.baseWidth = width;
  13834. depthTexture.baseHeight = height;
  13835. depthTexture.width = width;
  13836. depthTexture.height = height;
  13837. depthTexture.isReady = true;
  13838. depthTexture.samples = 1;
  13839. depthTexture.generateMipMaps = generateMipMaps;
  13840. depthTexture.samplingMode = gl.NEAREST;
  13841. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13842. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13843. textures.push(depthTexture);
  13844. this._internalTexturesCache.push(depthTexture);
  13845. }
  13846. gl.drawBuffers(attachments);
  13847. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13848. this.bindUnboundFramebuffer(null);
  13849. this.resetTextureCache();
  13850. return textures;
  13851. };
  13852. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13853. if (samples === void 0) { samples = 1; }
  13854. var depthStencilBuffer = null;
  13855. var gl = this._gl;
  13856. // Create the depth/stencil buffer
  13857. if (generateStencilBuffer) {
  13858. depthStencilBuffer = gl.createRenderbuffer();
  13859. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13860. if (samples > 1) {
  13861. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13862. }
  13863. else {
  13864. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13865. }
  13866. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13867. }
  13868. else if (generateDepthBuffer) {
  13869. depthStencilBuffer = gl.createRenderbuffer();
  13870. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13871. if (samples > 1) {
  13872. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13873. }
  13874. else {
  13875. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13876. }
  13877. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13878. }
  13879. return depthStencilBuffer;
  13880. };
  13881. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13882. if (this.webGLVersion < 2 || !texture) {
  13883. return 1;
  13884. }
  13885. if (texture.samples === samples) {
  13886. return samples;
  13887. }
  13888. var gl = this._gl;
  13889. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13890. // Dispose previous render buffers
  13891. if (texture._depthStencilBuffer) {
  13892. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13893. texture._depthStencilBuffer = null;
  13894. }
  13895. if (texture._MSAAFramebuffer) {
  13896. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13897. texture._MSAAFramebuffer = null;
  13898. }
  13899. if (texture._MSAARenderBuffer) {
  13900. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13901. texture._MSAARenderBuffer = null;
  13902. }
  13903. if (samples > 1) {
  13904. var framebuffer = gl.createFramebuffer();
  13905. if (!framebuffer) {
  13906. throw new Error("Unable to create multi sampled framebuffer");
  13907. }
  13908. texture._MSAAFramebuffer = framebuffer;
  13909. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13910. var colorRenderbuffer = gl.createRenderbuffer();
  13911. if (!colorRenderbuffer) {
  13912. throw new Error("Unable to create multi sampled framebuffer");
  13913. }
  13914. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13915. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13916. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13917. texture._MSAARenderBuffer = colorRenderbuffer;
  13918. }
  13919. else {
  13920. this.bindUnboundFramebuffer(texture._framebuffer);
  13921. }
  13922. texture.samples = samples;
  13923. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13924. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13925. this.bindUnboundFramebuffer(null);
  13926. return samples;
  13927. };
  13928. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13929. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13930. return 1;
  13931. }
  13932. if (textures[0].samples === samples) {
  13933. return samples;
  13934. }
  13935. var gl = this._gl;
  13936. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13937. // Dispose previous render buffers
  13938. if (textures[0]._depthStencilBuffer) {
  13939. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13940. textures[0]._depthStencilBuffer = null;
  13941. }
  13942. if (textures[0]._MSAAFramebuffer) {
  13943. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13944. textures[0]._MSAAFramebuffer = null;
  13945. }
  13946. for (var i = 0; i < textures.length; i++) {
  13947. if (textures[i]._MSAARenderBuffer) {
  13948. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13949. textures[i]._MSAARenderBuffer = null;
  13950. }
  13951. }
  13952. if (samples > 1) {
  13953. var framebuffer = gl.createFramebuffer();
  13954. if (!framebuffer) {
  13955. throw new Error("Unable to create multi sampled framebuffer");
  13956. }
  13957. this.bindUnboundFramebuffer(framebuffer);
  13958. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13959. var attachments = [];
  13960. for (var i = 0; i < textures.length; i++) {
  13961. var texture = textures[i];
  13962. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13963. var colorRenderbuffer = gl.createRenderbuffer();
  13964. if (!colorRenderbuffer) {
  13965. throw new Error("Unable to create multi sampled framebuffer");
  13966. }
  13967. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13968. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13969. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13970. texture._MSAAFramebuffer = framebuffer;
  13971. texture._MSAARenderBuffer = colorRenderbuffer;
  13972. texture.samples = samples;
  13973. texture._depthStencilBuffer = depthStencilBuffer;
  13974. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13975. attachments.push(attachment);
  13976. }
  13977. gl.drawBuffers(attachments);
  13978. }
  13979. else {
  13980. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13981. }
  13982. this.bindUnboundFramebuffer(null);
  13983. return samples;
  13984. };
  13985. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13986. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13987. };
  13988. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13989. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13990. };
  13991. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13992. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13993. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13994. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13995. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13996. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13997. }
  13998. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13999. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14000. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14001. }
  14002. var gl = this._gl;
  14003. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14004. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14005. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  14006. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14007. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14008. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  14009. }
  14010. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14011. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14012. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14013. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14014. for (var face = 0; face < 6; face++) {
  14015. 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);
  14016. }
  14017. // Create the framebuffer
  14018. var framebuffer = gl.createFramebuffer();
  14019. this.bindUnboundFramebuffer(framebuffer);
  14020. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  14021. // MipMaps
  14022. if (fullOptions.generateMipMaps) {
  14023. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14024. }
  14025. // Unbind
  14026. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14027. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14028. this.bindUnboundFramebuffer(null);
  14029. texture._framebuffer = framebuffer;
  14030. texture.width = size;
  14031. texture.height = size;
  14032. texture.isReady = true;
  14033. texture.isCube = true;
  14034. texture.samples = 1;
  14035. texture.generateMipMaps = fullOptions.generateMipMaps;
  14036. texture.samplingMode = fullOptions.samplingMode;
  14037. texture.type = fullOptions.type;
  14038. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14039. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  14040. this._internalTexturesCache.push(texture);
  14041. return texture;
  14042. };
  14043. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14044. var _this = this;
  14045. if (onLoad === void 0) { onLoad = null; }
  14046. if (onError === void 0) { onError = null; }
  14047. if (forcedExtension === void 0) { forcedExtension = null; }
  14048. var callback = function (loadData) {
  14049. if (!loadData) {
  14050. if (onLoad) {
  14051. onLoad(null);
  14052. }
  14053. return;
  14054. }
  14055. var texture = loadData.texture;
  14056. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14057. texture._lodGenerationScale = scale;
  14058. texture._lodGenerationOffset = offset;
  14059. if (_this._caps.textureLOD) {
  14060. // Do not add extra process if texture lod is supported.
  14061. if (onLoad) {
  14062. onLoad(texture);
  14063. }
  14064. return;
  14065. }
  14066. var mipSlices = 3;
  14067. var gl = _this._gl;
  14068. var width = loadData.width;
  14069. if (!width) {
  14070. return;
  14071. }
  14072. var textures = [];
  14073. for (var i = 0; i < mipSlices; i++) {
  14074. //compute LOD from even spacing in smoothness (matching shader calculation)
  14075. var smoothness = i / (mipSlices - 1);
  14076. var roughness = 1 - smoothness;
  14077. var minLODIndex = offset; // roughness = 0
  14078. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14079. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14080. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14081. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14082. glTextureFromLod.isCube = true;
  14083. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14084. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14085. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14087. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14088. if (loadData.isDDS) {
  14089. var info = loadData.info;
  14090. var data = loadData.data;
  14091. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14092. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14093. }
  14094. else {
  14095. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14096. }
  14097. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14098. // Wrap in a base texture for easy binding.
  14099. var lodTexture = new BABYLON.BaseTexture(scene);
  14100. lodTexture.isCube = true;
  14101. lodTexture._texture = glTextureFromLod;
  14102. glTextureFromLod.isReady = true;
  14103. textures.push(lodTexture);
  14104. }
  14105. texture._lodTextureHigh = textures[2];
  14106. texture._lodTextureMid = textures[1];
  14107. texture._lodTextureLow = textures[0];
  14108. if (onLoad) {
  14109. onLoad(texture);
  14110. }
  14111. };
  14112. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14113. };
  14114. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14115. var _this = this;
  14116. if (onLoad === void 0) { onLoad = null; }
  14117. if (onError === void 0) { onError = null; }
  14118. if (forcedExtension === void 0) { forcedExtension = null; }
  14119. var gl = this._gl;
  14120. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14121. texture.isCube = true;
  14122. texture.url = rootUrl;
  14123. texture.generateMipMaps = !noMipmap;
  14124. if (!this._doNotHandleContextLost) {
  14125. texture._extension = forcedExtension;
  14126. texture._files = files;
  14127. }
  14128. var isKTX = false;
  14129. var isDDS = false;
  14130. var lastDot = rootUrl.lastIndexOf('.');
  14131. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14132. if (this._textureFormatInUse) {
  14133. extension = this._textureFormatInUse;
  14134. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14135. isKTX = true;
  14136. }
  14137. else {
  14138. isDDS = (extension === ".dds");
  14139. }
  14140. var onerror = function (request, exception) {
  14141. if (onError && request) {
  14142. onError(request.status + " " + request.statusText, exception);
  14143. }
  14144. };
  14145. if (isKTX) {
  14146. this._loadFile(rootUrl, function (data) {
  14147. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14148. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14149. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14150. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14151. ktx.uploadLevels(_this._gl, !noMipmap);
  14152. _this.setCubeMapTextureParams(gl, loadMipmap);
  14153. texture.width = ktx.pixelWidth;
  14154. texture.height = ktx.pixelHeight;
  14155. texture.isReady = true;
  14156. }, undefined, undefined, true, onerror);
  14157. }
  14158. else if (isDDS) {
  14159. if (files && files.length === 6) {
  14160. this._cascadeLoadFiles(scene, function (imgs) {
  14161. var info;
  14162. var loadMipmap = false;
  14163. var width = 0;
  14164. for (var index = 0; index < imgs.length; index++) {
  14165. var data = imgs[index];
  14166. info = BABYLON.DDSTools.GetDDSInfo(data);
  14167. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14168. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14169. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14170. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14171. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14172. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14173. }
  14174. texture.width = info.width;
  14175. texture.height = info.height;
  14176. texture.type = info.textureType;
  14177. width = info.width;
  14178. }
  14179. _this.setCubeMapTextureParams(gl, loadMipmap);
  14180. texture.isReady = true;
  14181. if (onLoad) {
  14182. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14183. }
  14184. }, files, onError);
  14185. }
  14186. else {
  14187. this._loadFile(rootUrl, function (data) {
  14188. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14189. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14190. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14191. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14192. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14193. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14194. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14195. }
  14196. _this.setCubeMapTextureParams(gl, loadMipmap);
  14197. texture.width = info.width;
  14198. texture.height = info.height;
  14199. texture.isReady = true;
  14200. texture.type = info.textureType;
  14201. if (onLoad) {
  14202. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14203. }
  14204. }, undefined, undefined, true, onerror);
  14205. }
  14206. }
  14207. else {
  14208. if (!files) {
  14209. throw new Error("Cannot load cubemap because files were not defined");
  14210. }
  14211. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14212. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14213. var height = width;
  14214. _this._prepareWorkingCanvas();
  14215. if (!_this._workingCanvas || !_this._workingContext) {
  14216. return;
  14217. }
  14218. _this._workingCanvas.width = width;
  14219. _this._workingCanvas.height = height;
  14220. var faces = [
  14221. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14222. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14223. ];
  14224. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14225. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14226. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14227. for (var index = 0; index < faces.length; index++) {
  14228. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14229. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14230. }
  14231. if (!noMipmap) {
  14232. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14233. }
  14234. _this.setCubeMapTextureParams(gl, !noMipmap);
  14235. texture.width = width;
  14236. texture.height = height;
  14237. texture.isReady = true;
  14238. if (format) {
  14239. texture.format = format;
  14240. }
  14241. texture.onLoadedObservable.notifyObservers(texture);
  14242. texture.onLoadedObservable.clear();
  14243. if (onLoad) {
  14244. onLoad();
  14245. }
  14246. }, files, onError);
  14247. }
  14248. this._internalTexturesCache.push(texture);
  14249. return texture;
  14250. };
  14251. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14252. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14253. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14255. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14256. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14257. // this.resetTextureCache();
  14258. };
  14259. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14260. if (compression === void 0) { compression = null; }
  14261. if (level === void 0) { level = 0; }
  14262. texture._bufferViewArray = data;
  14263. texture.format = format;
  14264. texture.type = type;
  14265. texture.invertY = invertY;
  14266. texture._compression = compression;
  14267. var gl = this._gl;
  14268. var textureType = this._getWebGLTextureType(type);
  14269. var internalFormat = this._getInternalFormat(format);
  14270. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14271. var needConversion = false;
  14272. if (internalFormat === gl.RGB) {
  14273. internalFormat = gl.RGBA;
  14274. needConversion = true;
  14275. }
  14276. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14277. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14278. if (texture.width % 4 !== 0) {
  14279. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14280. }
  14281. // Data are known to be in +X +Y +Z -X -Y -Z
  14282. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14283. var faceData = data[faceIndex];
  14284. if (compression) {
  14285. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14286. }
  14287. else {
  14288. if (needConversion) {
  14289. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14290. }
  14291. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14292. }
  14293. }
  14294. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14295. if (isPot && texture.generateMipMaps && level === 0) {
  14296. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14297. }
  14298. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14299. // this.resetTextureCache();
  14300. texture.isReady = true;
  14301. };
  14302. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14303. if (compression === void 0) { compression = null; }
  14304. var gl = this._gl;
  14305. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14306. texture.isCube = true;
  14307. texture.generateMipMaps = generateMipMaps;
  14308. texture.format = format;
  14309. texture.type = type;
  14310. if (!this._doNotHandleContextLost) {
  14311. texture._bufferViewArray = data;
  14312. }
  14313. var textureType = this._getWebGLTextureType(type);
  14314. var internalFormat = this._getInternalFormat(format);
  14315. if (internalFormat === gl.RGB) {
  14316. internalFormat = gl.RGBA;
  14317. }
  14318. var width = size;
  14319. var height = width;
  14320. texture.width = width;
  14321. texture.height = height;
  14322. // Double check on POT to generate Mips.
  14323. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14324. if (!isPot) {
  14325. generateMipMaps = false;
  14326. }
  14327. // Upload data if needed. The texture won't be ready until then.
  14328. if (data) {
  14329. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14330. }
  14331. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14332. // Filters
  14333. if (data && generateMipMaps) {
  14334. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14335. }
  14336. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14337. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14338. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14339. }
  14340. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14341. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14342. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14343. }
  14344. else {
  14345. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14346. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14347. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14348. }
  14349. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14350. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14351. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14352. return texture;
  14353. };
  14354. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14355. var _this = this;
  14356. if (onLoad === void 0) { onLoad = null; }
  14357. if (onError === void 0) { onError = null; }
  14358. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14359. if (invertY === void 0) { invertY = false; }
  14360. var gl = this._gl;
  14361. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14362. scene._addPendingData(texture);
  14363. texture.url = url;
  14364. this._internalTexturesCache.push(texture);
  14365. var onerror = function (request, exception) {
  14366. scene._removePendingData(texture);
  14367. if (onError && request) {
  14368. onError(request.status + " " + request.statusText, exception);
  14369. }
  14370. };
  14371. var internalCallback = function (data) {
  14372. var width = texture.width;
  14373. var faceDataArrays = callback(data);
  14374. if (!faceDataArrays) {
  14375. return;
  14376. }
  14377. if (mipmmapGenerator) {
  14378. var textureType = _this._getWebGLTextureType(type);
  14379. var internalFormat = _this._getInternalFormat(format);
  14380. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14381. var needConversion = false;
  14382. if (internalFormat === gl.RGB) {
  14383. internalFormat = gl.RGBA;
  14384. needConversion = true;
  14385. }
  14386. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14387. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14388. var mipData = mipmmapGenerator(faceDataArrays);
  14389. for (var level = 0; level < mipData.length; level++) {
  14390. var mipSize = width >> level;
  14391. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14392. var mipFaceData = mipData[level][faceIndex];
  14393. if (needConversion) {
  14394. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14395. }
  14396. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14397. }
  14398. }
  14399. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14400. }
  14401. else {
  14402. texture.generateMipMaps = !noMipmap;
  14403. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14404. }
  14405. texture.isReady = true;
  14406. // this.resetTextureCache();
  14407. scene._removePendingData(texture);
  14408. if (onLoad) {
  14409. onLoad();
  14410. }
  14411. };
  14412. this._loadFile(url, function (data) {
  14413. internalCallback(data);
  14414. }, undefined, scene.database, true, onerror);
  14415. return texture;
  14416. };
  14417. ;
  14418. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14419. if (compression === void 0) { compression = null; }
  14420. var internalFormat = this._getInternalFormat(format);
  14421. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14422. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14423. if (!this._doNotHandleContextLost) {
  14424. texture._bufferView = data;
  14425. texture.format = format;
  14426. texture.invertY = invertY;
  14427. texture._compression = compression;
  14428. }
  14429. if (texture.width % 4 !== 0) {
  14430. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14431. }
  14432. if (compression && data) {
  14433. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14434. }
  14435. else {
  14436. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14437. }
  14438. if (texture.generateMipMaps) {
  14439. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14440. }
  14441. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14442. // this.resetTextureCache();
  14443. texture.isReady = true;
  14444. };
  14445. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14446. if (compression === void 0) { compression = null; }
  14447. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14448. texture.baseWidth = width;
  14449. texture.baseHeight = height;
  14450. texture.baseDepth = depth;
  14451. texture.width = width;
  14452. texture.height = height;
  14453. texture.depth = depth;
  14454. texture.format = format;
  14455. texture.generateMipMaps = generateMipMaps;
  14456. texture.samplingMode = samplingMode;
  14457. texture.is3D = true;
  14458. if (!this._doNotHandleContextLost) {
  14459. texture._bufferView = data;
  14460. }
  14461. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14462. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14463. // Filters
  14464. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14465. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14466. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14467. if (generateMipMaps) {
  14468. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14469. }
  14470. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14471. this._internalTexturesCache.push(texture);
  14472. return texture;
  14473. };
  14474. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14475. var gl = this._gl;
  14476. if (!gl) {
  14477. return;
  14478. }
  14479. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14480. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14481. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14482. if (!noMipmap && !isCompressed) {
  14483. gl.generateMipmap(gl.TEXTURE_2D);
  14484. }
  14485. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14486. // this.resetTextureCache();
  14487. if (scene) {
  14488. scene._removePendingData(texture);
  14489. }
  14490. texture.onLoadedObservable.notifyObservers(texture);
  14491. texture.onLoadedObservable.clear();
  14492. };
  14493. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14494. var _this = this;
  14495. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14496. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14497. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14498. var gl = this._gl;
  14499. if (!gl) {
  14500. return;
  14501. }
  14502. if (!texture._webGLTexture) {
  14503. // this.resetTextureCache();
  14504. if (scene) {
  14505. scene._removePendingData(texture);
  14506. }
  14507. return;
  14508. }
  14509. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14510. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14511. texture.baseWidth = width;
  14512. texture.baseHeight = height;
  14513. texture.width = potWidth;
  14514. texture.height = potHeight;
  14515. texture.isReady = true;
  14516. if (processFunction(potWidth, potHeight, function () {
  14517. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14518. })) {
  14519. // Returning as texture needs extra async steps
  14520. return;
  14521. }
  14522. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14523. };
  14524. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14525. // Create new RGBA data container.
  14526. var rgbaData;
  14527. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14528. rgbaData = new Float32Array(width * height * 4);
  14529. }
  14530. else {
  14531. rgbaData = new Uint32Array(width * height * 4);
  14532. }
  14533. // Convert each pixel.
  14534. for (var x = 0; x < width; x++) {
  14535. for (var y = 0; y < height; y++) {
  14536. var index = (y * width + x) * 3;
  14537. var newIndex = (y * width + x) * 4;
  14538. // Map Old Value to new value.
  14539. rgbaData[newIndex + 0] = rgbData[index + 0];
  14540. rgbaData[newIndex + 1] = rgbData[index + 1];
  14541. rgbaData[newIndex + 2] = rgbData[index + 2];
  14542. // Add fully opaque alpha channel.
  14543. rgbaData[newIndex + 3] = 1;
  14544. }
  14545. }
  14546. return rgbaData;
  14547. };
  14548. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14549. var gl = this._gl;
  14550. if (texture._framebuffer) {
  14551. gl.deleteFramebuffer(texture._framebuffer);
  14552. texture._framebuffer = null;
  14553. }
  14554. if (texture._depthStencilBuffer) {
  14555. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14556. texture._depthStencilBuffer = null;
  14557. }
  14558. if (texture._MSAAFramebuffer) {
  14559. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14560. texture._MSAAFramebuffer = null;
  14561. }
  14562. if (texture._MSAARenderBuffer) {
  14563. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14564. texture._MSAARenderBuffer = null;
  14565. }
  14566. };
  14567. Engine.prototype._releaseTexture = function (texture) {
  14568. var gl = this._gl;
  14569. this._releaseFramebufferObjects(texture);
  14570. gl.deleteTexture(texture._webGLTexture);
  14571. // Unbind channels
  14572. this.unbindAllTextures();
  14573. var index = this._internalTexturesCache.indexOf(texture);
  14574. if (index !== -1) {
  14575. this._internalTexturesCache.splice(index, 1);
  14576. }
  14577. // Integrated fixed lod samplers.
  14578. if (texture._lodTextureHigh) {
  14579. texture._lodTextureHigh.dispose();
  14580. }
  14581. if (texture._lodTextureMid) {
  14582. texture._lodTextureMid.dispose();
  14583. }
  14584. if (texture._lodTextureLow) {
  14585. texture._lodTextureLow.dispose();
  14586. }
  14587. // Set output texture of post process to null if the texture has been released/disposed
  14588. this.scenes.forEach(function (scene) {
  14589. scene.postProcesses.forEach(function (postProcess) {
  14590. if (postProcess._outputTexture == texture) {
  14591. postProcess._outputTexture = null;
  14592. }
  14593. });
  14594. scene.cameras.forEach(function (camera) {
  14595. camera._postProcesses.forEach(function (postProcess) {
  14596. if (postProcess) {
  14597. if (postProcess._outputTexture == texture) {
  14598. postProcess._outputTexture = null;
  14599. }
  14600. }
  14601. });
  14602. });
  14603. });
  14604. };
  14605. Engine.prototype.setProgram = function (program) {
  14606. if (this._currentProgram !== program) {
  14607. this._gl.useProgram(program);
  14608. this._currentProgram = program;
  14609. }
  14610. };
  14611. Engine.prototype.bindSamplers = function (effect) {
  14612. this.setProgram(effect.getProgram());
  14613. var samplers = effect.getSamplers();
  14614. for (var index = 0; index < samplers.length; index++) {
  14615. var uniform = effect.getUniform(samplers[index]);
  14616. if (uniform) {
  14617. this._boundUniforms[index] = uniform;
  14618. }
  14619. }
  14620. this._currentEffect = null;
  14621. };
  14622. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14623. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14624. return;
  14625. }
  14626. // Remove
  14627. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14628. // Bind last to it
  14629. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14630. // Bind to dummy
  14631. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14632. };
  14633. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14634. if (!internalTexture) {
  14635. return -1;
  14636. }
  14637. internalTexture._initialSlot = channel;
  14638. if (this.disableTextureBindingOptimization) {
  14639. if (channel !== internalTexture._designatedSlot) {
  14640. this._textureCollisions.addCount(1, false);
  14641. }
  14642. }
  14643. else {
  14644. if (channel !== internalTexture._designatedSlot) {
  14645. if (internalTexture._designatedSlot > -1) {
  14646. return internalTexture._designatedSlot;
  14647. }
  14648. else {
  14649. // No slot for this texture, let's pick a new one (if we find a free slot)
  14650. if (this._nextFreeTextureSlots.length) {
  14651. return this._nextFreeTextureSlots[0];
  14652. }
  14653. // We need to recycle the oldest bound texture, sorry.
  14654. this._textureCollisions.addCount(1, false);
  14655. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14656. }
  14657. }
  14658. }
  14659. return channel;
  14660. };
  14661. Engine.prototype._linkTrackers = function (previous, next) {
  14662. previous.next = next;
  14663. next.previous = previous;
  14664. };
  14665. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14666. var currentSlot = internalTexture._designatedSlot;
  14667. if (currentSlot === -1) {
  14668. return -1;
  14669. }
  14670. internalTexture._designatedSlot = -1;
  14671. if (this.disableTextureBindingOptimization) {
  14672. return -1;
  14673. }
  14674. // Remove from bound list
  14675. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14676. // Free the slot
  14677. this._boundTexturesCache[currentSlot] = null;
  14678. this._nextFreeTextureSlots.push(currentSlot);
  14679. return currentSlot;
  14680. };
  14681. Engine.prototype._activateCurrentTexture = function () {
  14682. if (this._currentTextureChannel !== this._activeChannel) {
  14683. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14684. this._currentTextureChannel = this._activeChannel;
  14685. }
  14686. };
  14687. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14688. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14689. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14690. this._activeChannel = texture._designatedSlot;
  14691. }
  14692. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14693. var isTextureForRendering = texture && texture._initialSlot > -1;
  14694. if (currentTextureBound !== texture) {
  14695. if (currentTextureBound) {
  14696. this._removeDesignatedSlot(currentTextureBound);
  14697. }
  14698. this._activateCurrentTexture();
  14699. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14700. this._boundTexturesCache[this._activeChannel] = texture;
  14701. if (texture) {
  14702. if (!this.disableTextureBindingOptimization) {
  14703. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14704. if (slotIndex > -1) {
  14705. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14706. }
  14707. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14708. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14709. }
  14710. texture._designatedSlot = this._activeChannel;
  14711. }
  14712. }
  14713. else if (forTextureDataUpdate) {
  14714. this._activateCurrentTexture();
  14715. }
  14716. if (isTextureForRendering && !forTextureDataUpdate) {
  14717. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14718. }
  14719. };
  14720. Engine.prototype._bindTexture = function (channel, texture) {
  14721. if (channel < 0) {
  14722. return;
  14723. }
  14724. if (texture) {
  14725. channel = this._getCorrectTextureChannel(channel, texture);
  14726. }
  14727. this._activeChannel = channel;
  14728. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14729. };
  14730. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14731. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14732. };
  14733. /**
  14734. * Binds the output of the passed in post process to the texture channel specified
  14735. * @param channel The channel the texture should be bound to
  14736. * @param postProcess The post process which's output should be bound
  14737. */
  14738. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14739. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14740. };
  14741. Engine.prototype.unbindAllTextures = function () {
  14742. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14743. this._activeChannel = channel;
  14744. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14745. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14746. if (this.webGLVersion > 1) {
  14747. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14748. }
  14749. }
  14750. };
  14751. /**
  14752. * Sets a texture to the according uniform.
  14753. * @param channel The texture channel
  14754. * @param uniform The uniform to set
  14755. * @param texture The texture to apply
  14756. */
  14757. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14758. if (channel < 0) {
  14759. return;
  14760. }
  14761. if (uniform) {
  14762. this._boundUniforms[channel] = uniform;
  14763. }
  14764. this._setTexture(channel, texture);
  14765. };
  14766. /**
  14767. * Sets a depth stencil texture from a render target to the according uniform.
  14768. * @param channel The texture channel
  14769. * @param uniform The uniform to set
  14770. * @param texture The render target texture containing the depth stencil texture to apply
  14771. */
  14772. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14773. if (channel < 0) {
  14774. return;
  14775. }
  14776. if (uniform) {
  14777. this._boundUniforms[channel] = uniform;
  14778. }
  14779. if (!texture || !texture.depthStencilTexture) {
  14780. this._setTexture(channel, null);
  14781. }
  14782. else {
  14783. this._setTexture(channel, texture, false, true);
  14784. }
  14785. };
  14786. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14787. var uniform = this._boundUniforms[sourceSlot];
  14788. if (uniform._currentState === destination) {
  14789. return;
  14790. }
  14791. this._gl.uniform1i(uniform, destination);
  14792. uniform._currentState = destination;
  14793. };
  14794. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14795. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14796. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14797. // Not ready?
  14798. if (!texture) {
  14799. if (this._boundTexturesCache[channel] != null) {
  14800. this._activeChannel = channel;
  14801. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14802. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14803. if (this.webGLVersion > 1) {
  14804. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14805. }
  14806. }
  14807. return false;
  14808. }
  14809. // Video
  14810. if (texture.video) {
  14811. this._activeChannel = channel;
  14812. texture.update();
  14813. }
  14814. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14815. texture.delayLoad();
  14816. return false;
  14817. }
  14818. var internalTexture;
  14819. if (depthStencilTexture) {
  14820. internalTexture = texture.depthStencilTexture;
  14821. }
  14822. else if (texture.isReady()) {
  14823. internalTexture = texture.getInternalTexture();
  14824. }
  14825. else if (texture.isCube) {
  14826. internalTexture = this.emptyCubeTexture;
  14827. }
  14828. else if (texture.is3D) {
  14829. internalTexture = this.emptyTexture3D;
  14830. }
  14831. else {
  14832. internalTexture = this.emptyTexture;
  14833. }
  14834. if (!isPartOfTextureArray) {
  14835. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14836. }
  14837. if (this._boundTexturesCache[channel] === internalTexture) {
  14838. this._moveBoundTextureOnTop(internalTexture);
  14839. if (!isPartOfTextureArray) {
  14840. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14841. }
  14842. return false;
  14843. }
  14844. this._activeChannel = channel;
  14845. if (internalTexture && internalTexture.is3D) {
  14846. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14847. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14848. internalTexture._cachedWrapU = texture.wrapU;
  14849. switch (texture.wrapU) {
  14850. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14851. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14852. break;
  14853. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14854. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14855. break;
  14856. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14857. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14858. break;
  14859. }
  14860. }
  14861. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14862. internalTexture._cachedWrapV = texture.wrapV;
  14863. switch (texture.wrapV) {
  14864. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14865. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14866. break;
  14867. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14868. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14869. break;
  14870. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14871. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14872. break;
  14873. }
  14874. }
  14875. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14876. internalTexture._cachedWrapR = texture.wrapR;
  14877. switch (texture.wrapR) {
  14878. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14879. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14880. break;
  14881. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14882. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14883. break;
  14884. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14885. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14886. break;
  14887. }
  14888. }
  14889. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14890. }
  14891. else if (internalTexture && internalTexture.isCube) {
  14892. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14893. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14894. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14895. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14896. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14897. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14898. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14899. }
  14900. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14901. }
  14902. else {
  14903. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14904. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14905. internalTexture._cachedWrapU = texture.wrapU;
  14906. switch (texture.wrapU) {
  14907. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14908. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14909. break;
  14910. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14911. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14912. break;
  14913. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14914. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14915. break;
  14916. }
  14917. }
  14918. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14919. internalTexture._cachedWrapV = texture.wrapV;
  14920. switch (texture.wrapV) {
  14921. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14922. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14923. break;
  14924. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14925. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14926. break;
  14927. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14928. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14929. break;
  14930. }
  14931. }
  14932. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14933. }
  14934. return true;
  14935. };
  14936. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14937. if (channel < 0 || !uniform) {
  14938. return;
  14939. }
  14940. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14941. this._textureUnits = new Int32Array(textures.length);
  14942. }
  14943. for (var i = 0; i < textures.length; i++) {
  14944. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14945. }
  14946. this._gl.uniform1iv(uniform, this._textureUnits);
  14947. for (var index = 0; index < textures.length; index++) {
  14948. this._setTexture(this._textureUnits[index], textures[index], true);
  14949. }
  14950. };
  14951. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14952. var internalTexture = texture.getInternalTexture();
  14953. if (!internalTexture) {
  14954. return;
  14955. }
  14956. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14957. var value = texture.anisotropicFilteringLevel;
  14958. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14959. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14960. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14961. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14962. }
  14963. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14964. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14965. internalTexture._cachedAnisotropicFilteringLevel = value;
  14966. }
  14967. };
  14968. Engine.prototype.readPixels = function (x, y, width, height) {
  14969. var data = new Uint8Array(height * width * 4);
  14970. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14971. return data;
  14972. };
  14973. /**
  14974. * Add an externaly attached data from its key.
  14975. * This method call will fail and return false, if such key already exists.
  14976. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14977. * @param key the unique key that identifies the data
  14978. * @param data the data object to associate to the key for this Engine instance
  14979. * @return true if no such key were already present and the data was added successfully, false otherwise
  14980. */
  14981. Engine.prototype.addExternalData = function (key, data) {
  14982. if (!this._externalData) {
  14983. this._externalData = new BABYLON.StringDictionary();
  14984. }
  14985. return this._externalData.add(key, data);
  14986. };
  14987. /**
  14988. * Get an externaly attached data from its key
  14989. * @param key the unique key that identifies the data
  14990. * @return the associated data, if present (can be null), or undefined if not present
  14991. */
  14992. Engine.prototype.getExternalData = function (key) {
  14993. if (!this._externalData) {
  14994. this._externalData = new BABYLON.StringDictionary();
  14995. }
  14996. return this._externalData.get(key);
  14997. };
  14998. /**
  14999. * Get an externaly attached data from its key, create it using a factory if it's not already present
  15000. * @param key the unique key that identifies the data
  15001. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  15002. * @return the associated data, can be null if the factory returned null.
  15003. */
  15004. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  15005. if (!this._externalData) {
  15006. this._externalData = new BABYLON.StringDictionary();
  15007. }
  15008. return this._externalData.getOrAddWithFactory(key, factory);
  15009. };
  15010. /**
  15011. * Remove an externaly attached data from the Engine instance
  15012. * @param key the unique key that identifies the data
  15013. * @return true if the data was successfully removed, false if it doesn't exist
  15014. */
  15015. Engine.prototype.removeExternalData = function (key) {
  15016. if (!this._externalData) {
  15017. this._externalData = new BABYLON.StringDictionary();
  15018. }
  15019. return this._externalData.remove(key);
  15020. };
  15021. Engine.prototype.unbindAllAttributes = function () {
  15022. if (this._mustWipeVertexAttributes) {
  15023. this._mustWipeVertexAttributes = false;
  15024. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  15025. this._gl.disableVertexAttribArray(i);
  15026. this._vertexAttribArraysEnabled[i] = false;
  15027. this._currentBufferPointers[i].active = false;
  15028. }
  15029. return;
  15030. }
  15031. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  15032. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  15033. continue;
  15034. }
  15035. this._gl.disableVertexAttribArray(i);
  15036. this._vertexAttribArraysEnabled[i] = false;
  15037. this._currentBufferPointers[i].active = false;
  15038. }
  15039. };
  15040. Engine.prototype.releaseEffects = function () {
  15041. for (var name in this._compiledEffects) {
  15042. this._deleteProgram(this._compiledEffects[name]._program);
  15043. }
  15044. this._compiledEffects = {};
  15045. };
  15046. // Dispose
  15047. Engine.prototype.dispose = function () {
  15048. this.hideLoadingUI();
  15049. this.stopRenderLoop();
  15050. // Release postProcesses
  15051. while (this.postProcesses.length) {
  15052. this.postProcesses[0].dispose();
  15053. }
  15054. // Empty texture
  15055. if (this._emptyTexture) {
  15056. this._releaseTexture(this._emptyTexture);
  15057. this._emptyTexture = null;
  15058. }
  15059. if (this._emptyCubeTexture) {
  15060. this._releaseTexture(this._emptyCubeTexture);
  15061. this._emptyCubeTexture = null;
  15062. }
  15063. // Rescale PP
  15064. if (this._rescalePostProcess) {
  15065. this._rescalePostProcess.dispose();
  15066. }
  15067. // Release scenes
  15068. while (this.scenes.length) {
  15069. this.scenes[0].dispose();
  15070. }
  15071. // Release audio engine
  15072. if (Engine.audioEngine) {
  15073. Engine.audioEngine.dispose();
  15074. }
  15075. // Release effects
  15076. this.releaseEffects();
  15077. // Unbind
  15078. this.unbindAllAttributes();
  15079. if (this._dummyFramebuffer) {
  15080. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15081. }
  15082. //WebVR
  15083. this.disableVR();
  15084. // Events
  15085. if (BABYLON.Tools.IsWindowObjectExist()) {
  15086. window.removeEventListener("blur", this._onBlur);
  15087. window.removeEventListener("focus", this._onFocus);
  15088. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15089. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15090. if (this._renderingCanvas) {
  15091. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15092. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15093. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15094. if (!this._doNotHandleContextLost) {
  15095. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15096. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15097. }
  15098. }
  15099. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15100. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15101. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15102. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15103. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15104. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15105. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15106. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15107. if (this._onVrDisplayConnect) {
  15108. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15109. if (this._onVrDisplayDisconnect) {
  15110. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15111. }
  15112. if (this._onVrDisplayPresentChange) {
  15113. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15114. }
  15115. this._onVrDisplayConnect = null;
  15116. this._onVrDisplayDisconnect = null;
  15117. }
  15118. }
  15119. // Remove from Instances
  15120. var index = Engine.Instances.indexOf(this);
  15121. if (index >= 0) {
  15122. Engine.Instances.splice(index, 1);
  15123. }
  15124. this._workingCanvas = null;
  15125. this._workingContext = null;
  15126. this._currentBufferPointers = [];
  15127. this._renderingCanvas = null;
  15128. this._currentProgram = null;
  15129. this._bindedRenderFunction = null;
  15130. this.onResizeObservable.clear();
  15131. this.onCanvasBlurObservable.clear();
  15132. this.onCanvasFocusObservable.clear();
  15133. this.onCanvasPointerOutObservable.clear();
  15134. this.onBeginFrameObservable.clear();
  15135. this.onEndFrameObservable.clear();
  15136. BABYLON.Effect.ResetCache();
  15137. // Abort active requests
  15138. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15139. var request = _a[_i];
  15140. request.abort();
  15141. }
  15142. };
  15143. // Loading screen
  15144. Engine.prototype.displayLoadingUI = function () {
  15145. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15146. return;
  15147. }
  15148. var loadingScreen = this.loadingScreen;
  15149. if (loadingScreen) {
  15150. loadingScreen.displayLoadingUI();
  15151. }
  15152. };
  15153. Engine.prototype.hideLoadingUI = function () {
  15154. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15155. return;
  15156. }
  15157. var loadingScreen = this.loadingScreen;
  15158. if (loadingScreen) {
  15159. loadingScreen.hideLoadingUI();
  15160. }
  15161. };
  15162. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15163. get: function () {
  15164. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15165. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15166. return this._loadingScreen;
  15167. },
  15168. set: function (loadingScreen) {
  15169. this._loadingScreen = loadingScreen;
  15170. },
  15171. enumerable: true,
  15172. configurable: true
  15173. });
  15174. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15175. set: function (text) {
  15176. this.loadingScreen.loadingUIText = text;
  15177. },
  15178. enumerable: true,
  15179. configurable: true
  15180. });
  15181. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15182. set: function (color) {
  15183. this.loadingScreen.loadingUIBackgroundColor = color;
  15184. },
  15185. enumerable: true,
  15186. configurable: true
  15187. });
  15188. Engine.prototype.attachContextLostEvent = function (callback) {
  15189. if (this._renderingCanvas) {
  15190. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15191. }
  15192. };
  15193. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15194. if (this._renderingCanvas) {
  15195. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15196. }
  15197. };
  15198. Engine.prototype.getVertexShaderSource = function (program) {
  15199. var shaders = this._gl.getAttachedShaders(program);
  15200. if (!shaders) {
  15201. return null;
  15202. }
  15203. return this._gl.getShaderSource(shaders[0]);
  15204. };
  15205. Engine.prototype.getFragmentShaderSource = function (program) {
  15206. var shaders = this._gl.getAttachedShaders(program);
  15207. if (!shaders) {
  15208. return null;
  15209. }
  15210. return this._gl.getShaderSource(shaders[1]);
  15211. };
  15212. Engine.prototype.getError = function () {
  15213. return this._gl.getError();
  15214. };
  15215. // FPS
  15216. Engine.prototype.getFps = function () {
  15217. return this._fps;
  15218. };
  15219. Engine.prototype.getDeltaTime = function () {
  15220. return this._deltaTime;
  15221. };
  15222. Engine.prototype._measureFps = function () {
  15223. this._performanceMonitor.sampleFrame();
  15224. this._fps = this._performanceMonitor.averageFPS;
  15225. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15226. };
  15227. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15228. if (faceIndex === void 0) { faceIndex = -1; }
  15229. var gl = this._gl;
  15230. if (!this._dummyFramebuffer) {
  15231. var dummy = gl.createFramebuffer();
  15232. if (!dummy) {
  15233. throw new Error("Unable to create dummy framebuffer");
  15234. }
  15235. this._dummyFramebuffer = dummy;
  15236. }
  15237. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15238. if (faceIndex > -1) {
  15239. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15240. }
  15241. else {
  15242. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15243. }
  15244. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15245. var buffer;
  15246. switch (readType) {
  15247. case gl.UNSIGNED_BYTE:
  15248. buffer = new Uint8Array(4 * width * height);
  15249. readType = gl.UNSIGNED_BYTE;
  15250. break;
  15251. default:
  15252. buffer = new Float32Array(4 * width * height);
  15253. readType = gl.FLOAT;
  15254. break;
  15255. }
  15256. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15257. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15258. return buffer;
  15259. };
  15260. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15261. if (this._webGLVersion > 1) {
  15262. return this._caps.colorBufferFloat;
  15263. }
  15264. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15265. };
  15266. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15267. if (this._webGLVersion > 1) {
  15268. return this._caps.colorBufferFloat;
  15269. }
  15270. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15271. };
  15272. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15273. Engine.prototype._canRenderToFramebuffer = function (type) {
  15274. var gl = this._gl;
  15275. //clear existing errors
  15276. while (gl.getError() !== gl.NO_ERROR) { }
  15277. var successful = true;
  15278. var texture = gl.createTexture();
  15279. gl.bindTexture(gl.TEXTURE_2D, texture);
  15280. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15281. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15283. var fb = gl.createFramebuffer();
  15284. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15285. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15286. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15287. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15288. successful = successful && (gl.getError() === gl.NO_ERROR);
  15289. //try render by clearing frame buffer's color buffer
  15290. if (successful) {
  15291. gl.clear(gl.COLOR_BUFFER_BIT);
  15292. successful = successful && (gl.getError() === gl.NO_ERROR);
  15293. }
  15294. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15295. if (successful) {
  15296. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15297. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15298. var readFormat = gl.RGBA;
  15299. var readType = gl.UNSIGNED_BYTE;
  15300. var buffer = new Uint8Array(4);
  15301. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15302. successful = successful && (gl.getError() === gl.NO_ERROR);
  15303. }
  15304. //clean up
  15305. gl.deleteTexture(texture);
  15306. gl.deleteFramebuffer(fb);
  15307. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15308. //clear accumulated errors
  15309. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15310. return successful;
  15311. };
  15312. Engine.prototype._getWebGLTextureType = function (type) {
  15313. if (type === Engine.TEXTURETYPE_FLOAT) {
  15314. return this._gl.FLOAT;
  15315. }
  15316. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15317. // Add Half Float Constant.
  15318. return this._gl.HALF_FLOAT_OES;
  15319. }
  15320. return this._gl.UNSIGNED_BYTE;
  15321. };
  15322. ;
  15323. Engine.prototype._getInternalFormat = function (format) {
  15324. var internalFormat = this._gl.RGBA;
  15325. switch (format) {
  15326. case Engine.TEXTUREFORMAT_ALPHA:
  15327. internalFormat = this._gl.ALPHA;
  15328. break;
  15329. case Engine.TEXTUREFORMAT_LUMINANCE:
  15330. internalFormat = this._gl.LUMINANCE;
  15331. break;
  15332. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15333. internalFormat = this._gl.LUMINANCE_ALPHA;
  15334. break;
  15335. case Engine.TEXTUREFORMAT_RGB:
  15336. case Engine.TEXTUREFORMAT_RGB32F:
  15337. internalFormat = this._gl.RGB;
  15338. break;
  15339. case Engine.TEXTUREFORMAT_RGBA:
  15340. case Engine.TEXTUREFORMAT_RGBA32F:
  15341. internalFormat = this._gl.RGBA;
  15342. break;
  15343. case Engine.TEXTUREFORMAT_R32F:
  15344. internalFormat = this._gl.RED;
  15345. break;
  15346. case Engine.TEXTUREFORMAT_RG32F:
  15347. internalFormat = this._gl.RG;
  15348. break;
  15349. }
  15350. return internalFormat;
  15351. };
  15352. /** @ignore */
  15353. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15354. if (this._webGLVersion === 1) {
  15355. if (format) {
  15356. switch (format) {
  15357. case Engine.TEXTUREFORMAT_LUMINANCE:
  15358. return this._gl.LUMINANCE;
  15359. }
  15360. }
  15361. return this._gl.RGBA;
  15362. }
  15363. if (type === Engine.TEXTURETYPE_FLOAT) {
  15364. if (format) {
  15365. switch (format) {
  15366. case Engine.TEXTUREFORMAT_R32F:
  15367. return this._gl.R32F;
  15368. case Engine.TEXTUREFORMAT_RG32F:
  15369. return this._gl.RG32F;
  15370. case Engine.TEXTUREFORMAT_RGB32F:
  15371. return this._gl.RGB32F;
  15372. }
  15373. }
  15374. return this._gl.RGBA32F;
  15375. }
  15376. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15377. return this._gl.RGBA16F;
  15378. }
  15379. if (format) {
  15380. switch (format) {
  15381. case Engine.TEXTUREFORMAT_LUMINANCE:
  15382. return this._gl.LUMINANCE;
  15383. }
  15384. }
  15385. return this._gl.RGBA;
  15386. };
  15387. ;
  15388. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15389. if (type === Engine.TEXTURETYPE_FLOAT) {
  15390. return this._gl.RGBA32F;
  15391. }
  15392. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15393. return this._gl.RGBA16F;
  15394. }
  15395. return this._gl.RGBA8;
  15396. };
  15397. ;
  15398. Engine.prototype.createQuery = function () {
  15399. return this._gl.createQuery();
  15400. };
  15401. Engine.prototype.deleteQuery = function (query) {
  15402. this._gl.deleteQuery(query);
  15403. return this;
  15404. };
  15405. Engine.prototype.isQueryResultAvailable = function (query) {
  15406. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15407. };
  15408. Engine.prototype.getQueryResult = function (query) {
  15409. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15410. };
  15411. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15412. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15413. this._gl.beginQuery(glAlgorithm, query);
  15414. return this;
  15415. };
  15416. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15417. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15418. this._gl.endQuery(glAlgorithm);
  15419. return this;
  15420. };
  15421. /* Time queries */
  15422. Engine.prototype._createTimeQuery = function () {
  15423. var timerQuery = this._caps.timerQuery;
  15424. if (timerQuery.createQueryEXT) {
  15425. return timerQuery.createQueryEXT();
  15426. }
  15427. return this.createQuery();
  15428. };
  15429. Engine.prototype._deleteTimeQuery = function (query) {
  15430. var timerQuery = this._caps.timerQuery;
  15431. if (timerQuery.deleteQueryEXT) {
  15432. timerQuery.deleteQueryEXT(query);
  15433. return;
  15434. }
  15435. this.deleteQuery(query);
  15436. };
  15437. Engine.prototype._getTimeQueryResult = function (query) {
  15438. var timerQuery = this._caps.timerQuery;
  15439. if (timerQuery.getQueryObjectEXT) {
  15440. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15441. }
  15442. return this.getQueryResult(query);
  15443. };
  15444. Engine.prototype._getTimeQueryAvailability = function (query) {
  15445. var timerQuery = this._caps.timerQuery;
  15446. if (timerQuery.getQueryObjectEXT) {
  15447. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15448. }
  15449. return this.isQueryResultAvailable(query);
  15450. };
  15451. Engine.prototype.startTimeQuery = function () {
  15452. var timerQuery = this._caps.timerQuery;
  15453. if (!timerQuery) {
  15454. return null;
  15455. }
  15456. var token = new BABYLON._TimeToken();
  15457. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15458. if (this._caps.canUseTimestampForTimerQuery) {
  15459. token._startTimeQuery = this._createTimeQuery();
  15460. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15461. }
  15462. else {
  15463. if (this._currentNonTimestampToken) {
  15464. return this._currentNonTimestampToken;
  15465. }
  15466. token._timeElapsedQuery = this._createTimeQuery();
  15467. if (timerQuery.beginQueryEXT) {
  15468. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15469. }
  15470. else {
  15471. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15472. }
  15473. this._currentNonTimestampToken = token;
  15474. }
  15475. return token;
  15476. };
  15477. Engine.prototype.endTimeQuery = function (token) {
  15478. var timerQuery = this._caps.timerQuery;
  15479. if (!timerQuery || !token) {
  15480. return -1;
  15481. }
  15482. if (this._caps.canUseTimestampForTimerQuery) {
  15483. if (!token._startTimeQuery) {
  15484. return -1;
  15485. }
  15486. if (!token._endTimeQuery) {
  15487. token._endTimeQuery = this._createTimeQuery();
  15488. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15489. }
  15490. }
  15491. else if (!token._timeElapsedQueryEnded) {
  15492. if (!token._timeElapsedQuery) {
  15493. return -1;
  15494. }
  15495. if (timerQuery.endQueryEXT) {
  15496. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15497. }
  15498. else {
  15499. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15500. }
  15501. token._timeElapsedQueryEnded = true;
  15502. }
  15503. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15504. var available = false;
  15505. if (token._endTimeQuery) {
  15506. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15507. }
  15508. else if (token._timeElapsedQuery) {
  15509. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15510. }
  15511. if (available && !disjoint) {
  15512. var result = 0;
  15513. if (this._caps.canUseTimestampForTimerQuery) {
  15514. if (!token._startTimeQuery || !token._endTimeQuery) {
  15515. return -1;
  15516. }
  15517. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15518. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15519. result = timeEnd - timeStart;
  15520. this._deleteTimeQuery(token._startTimeQuery);
  15521. this._deleteTimeQuery(token._endTimeQuery);
  15522. token._startTimeQuery = null;
  15523. token._endTimeQuery = null;
  15524. }
  15525. else {
  15526. if (!token._timeElapsedQuery) {
  15527. return -1;
  15528. }
  15529. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15530. this._deleteTimeQuery(token._timeElapsedQuery);
  15531. token._timeElapsedQuery = null;
  15532. token._timeElapsedQueryEnded = false;
  15533. this._currentNonTimestampToken = null;
  15534. }
  15535. return result;
  15536. }
  15537. return -1;
  15538. };
  15539. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15540. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15541. };
  15542. // Transform feedback
  15543. Engine.prototype.createTransformFeedback = function () {
  15544. return this._gl.createTransformFeedback();
  15545. };
  15546. Engine.prototype.deleteTransformFeedback = function (value) {
  15547. this._gl.deleteTransformFeedback(value);
  15548. };
  15549. Engine.prototype.bindTransformFeedback = function (value) {
  15550. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15551. };
  15552. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15553. if (usePoints === void 0) { usePoints = true; }
  15554. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15555. };
  15556. Engine.prototype.endTransformFeedback = function () {
  15557. this._gl.endTransformFeedback();
  15558. };
  15559. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15560. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15561. };
  15562. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15563. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15564. };
  15565. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15566. var _this = this;
  15567. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15568. this._activeRequests.push(request);
  15569. request.onCompleteObservable.add(function (request) {
  15570. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15571. });
  15572. return request;
  15573. };
  15574. /** @ignore */
  15575. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15576. var _this = this;
  15577. return new Promise(function (resolve, reject) {
  15578. _this._loadFile(url, function (data) {
  15579. resolve(data);
  15580. }, undefined, database, useArrayBuffer, function (request, exception) {
  15581. reject(exception);
  15582. });
  15583. });
  15584. };
  15585. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15586. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15587. var onload = function (data) {
  15588. loadedFiles[index] = data;
  15589. loadedFiles._internalCount++;
  15590. if (loadedFiles._internalCount === 6) {
  15591. onfinish(loadedFiles);
  15592. }
  15593. };
  15594. var onerror = function (request, exception) {
  15595. if (onErrorCallBack && request) {
  15596. onErrorCallBack(request.status + " " + request.statusText, exception);
  15597. }
  15598. };
  15599. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15600. };
  15601. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15602. if (onError === void 0) { onError = null; }
  15603. var loadedFiles = [];
  15604. loadedFiles._internalCount = 0;
  15605. for (var index = 0; index < 6; index++) {
  15606. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15607. }
  15608. };
  15609. // Statics
  15610. Engine.isSupported = function () {
  15611. try {
  15612. var tempcanvas = document.createElement("canvas");
  15613. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15614. return gl != null && !!window.WebGLRenderingContext;
  15615. }
  15616. catch (e) {
  15617. return false;
  15618. }
  15619. };
  15620. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15621. Engine.ExceptionList = [
  15622. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15623. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15624. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15625. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15626. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15627. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15628. ];
  15629. Engine.Instances = new Array();
  15630. // Const statics
  15631. Engine._ALPHA_DISABLE = 0;
  15632. Engine._ALPHA_ADD = 1;
  15633. Engine._ALPHA_COMBINE = 2;
  15634. Engine._ALPHA_SUBTRACT = 3;
  15635. Engine._ALPHA_MULTIPLY = 4;
  15636. Engine._ALPHA_MAXIMIZED = 5;
  15637. Engine._ALPHA_ONEONE = 6;
  15638. Engine._ALPHA_PREMULTIPLIED = 7;
  15639. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15640. Engine._ALPHA_INTERPOLATE = 9;
  15641. Engine._ALPHA_SCREENMODE = 10;
  15642. Engine._DELAYLOADSTATE_NONE = 0;
  15643. Engine._DELAYLOADSTATE_LOADED = 1;
  15644. Engine._DELAYLOADSTATE_LOADING = 2;
  15645. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15646. Engine._TEXTUREFORMAT_ALPHA = 0;
  15647. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15648. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15649. Engine._TEXTUREFORMAT_RGB = 4;
  15650. Engine._TEXTUREFORMAT_RGBA = 5;
  15651. Engine._TEXTUREFORMAT_R32F = 6;
  15652. Engine._TEXTUREFORMAT_RG32F = 7;
  15653. Engine._TEXTUREFORMAT_RGB32F = 8;
  15654. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15655. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15656. Engine._TEXTURETYPE_FLOAT = 1;
  15657. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15658. // Depht or Stencil test Constants.
  15659. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15660. 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.
  15661. 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.
  15662. 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.
  15663. 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.
  15664. 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.
  15665. 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.
  15666. 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.
  15667. // Stencil Actions Constants.
  15668. Engine._KEEP = 0x1E00;
  15669. Engine._REPLACE = 0x1E01;
  15670. Engine._INCR = 0x1E02;
  15671. Engine._DECR = 0x1E03;
  15672. Engine._INVERT = 0x150A;
  15673. Engine._INCR_WRAP = 0x8507;
  15674. Engine._DECR_WRAP = 0x8508;
  15675. // Texture rescaling mode
  15676. Engine._SCALEMODE_FLOOR = 1;
  15677. Engine._SCALEMODE_NEAREST = 2;
  15678. Engine._SCALEMODE_CEILING = 3;
  15679. // Updatable statics so stick with vars here
  15680. Engine.CollisionsEpsilon = 0.001;
  15681. Engine.CodeRepository = "src/";
  15682. Engine.ShadersRepository = "src/Shaders/";
  15683. return Engine;
  15684. }());
  15685. BABYLON.Engine = Engine;
  15686. })(BABYLON || (BABYLON = {}));
  15687. //# sourceMappingURL=babylon.engine.js.map
  15688. "use strict";
  15689. var BABYLON;
  15690. (function (BABYLON) {
  15691. /**
  15692. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15693. */
  15694. var Node = /** @class */ (function () {
  15695. /**
  15696. * Creates a new Node
  15697. * @param {string} name - the name and id to be given to this node
  15698. * @param {BABYLON.Scene} the scene this node will be added to
  15699. */
  15700. function Node(name, scene) {
  15701. if (scene === void 0) { scene = null; }
  15702. /**
  15703. * Gets or sets a string used to store user defined state for the node
  15704. */
  15705. this.state = "";
  15706. /**
  15707. * Gets or sets an object used to store user defined information for the node
  15708. */
  15709. this.metadata = null;
  15710. /**
  15711. * Gets or sets a boolean used to define if the node must be serialized
  15712. */
  15713. this.doNotSerialize = false;
  15714. /** @ignore */
  15715. this._isDisposed = false;
  15716. /**
  15717. * Gets a list of {BABYLON.Animation} associated with the node
  15718. */
  15719. this.animations = new Array();
  15720. this._ranges = {};
  15721. this._isEnabled = true;
  15722. this._isReady = true;
  15723. /** @ignore */
  15724. this._currentRenderId = -1;
  15725. this._parentRenderId = -1;
  15726. this._animationPropertiesOverride = null;
  15727. /**
  15728. * An event triggered when the mesh is disposed
  15729. * @type {BABYLON.Observable}
  15730. */
  15731. this.onDisposeObservable = new BABYLON.Observable();
  15732. // Behaviors
  15733. this._behaviors = new Array();
  15734. this.name = name;
  15735. this.id = name;
  15736. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15737. this.uniqueId = this._scene.getUniqueId();
  15738. this._initCache();
  15739. }
  15740. /**
  15741. * Gets a boolean indicating if the node has been disposed
  15742. * @returns true if the node was disposed
  15743. */
  15744. Node.prototype.isDisposed = function () {
  15745. return this._isDisposed;
  15746. };
  15747. Object.defineProperty(Node.prototype, "parent", {
  15748. get: function () {
  15749. return this._parentNode;
  15750. },
  15751. /**
  15752. * Gets or sets the parent of the node
  15753. */
  15754. set: function (parent) {
  15755. if (this._parentNode === parent) {
  15756. return;
  15757. }
  15758. // Remove self from list of children of parent
  15759. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15760. var index = this._parentNode._children.indexOf(this);
  15761. if (index !== -1) {
  15762. this._parentNode._children.splice(index, 1);
  15763. }
  15764. }
  15765. // Store new parent
  15766. this._parentNode = parent;
  15767. // Add as child to new parent
  15768. if (this._parentNode) {
  15769. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15770. this._parentNode._children = new Array();
  15771. }
  15772. this._parentNode._children.push(this);
  15773. }
  15774. },
  15775. enumerable: true,
  15776. configurable: true
  15777. });
  15778. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15779. /**
  15780. * Gets or sets the animation properties override
  15781. */
  15782. get: function () {
  15783. return this._animationPropertiesOverride;
  15784. },
  15785. set: function (value) {
  15786. this._animationPropertiesOverride = value;
  15787. },
  15788. enumerable: true,
  15789. configurable: true
  15790. });
  15791. /**
  15792. * Gets a string idenfifying the name of the class
  15793. * @returns "Node" string
  15794. */
  15795. Node.prototype.getClassName = function () {
  15796. return "Node";
  15797. };
  15798. Object.defineProperty(Node.prototype, "onDispose", {
  15799. /**
  15800. * Sets a callback that will be raised when the node will be disposed
  15801. */
  15802. set: function (callback) {
  15803. if (this._onDisposeObserver) {
  15804. this.onDisposeObservable.remove(this._onDisposeObserver);
  15805. }
  15806. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15807. },
  15808. enumerable: true,
  15809. configurable: true
  15810. });
  15811. /**
  15812. * Gets the scene of the node
  15813. * @returns a {BABYLON.Scene}
  15814. */
  15815. Node.prototype.getScene = function () {
  15816. return this._scene;
  15817. };
  15818. /**
  15819. * Gets the engine of the node
  15820. * @returns a {BABYLON.Engine}
  15821. */
  15822. Node.prototype.getEngine = function () {
  15823. return this._scene.getEngine();
  15824. };
  15825. /**
  15826. * Attach a behavior to the node
  15827. * @see http://doc.babylonjs.com/features/behaviour
  15828. * @param behavior defines the behavior to attach
  15829. * @returns the current Node
  15830. */
  15831. Node.prototype.addBehavior = function (behavior) {
  15832. var _this = this;
  15833. var index = this._behaviors.indexOf(behavior);
  15834. if (index !== -1) {
  15835. return this;
  15836. }
  15837. behavior.init();
  15838. if (this._scene.isLoading) {
  15839. // We defer the attach when the scene will be loaded
  15840. var observer = this._scene.onDataLoadedObservable.add(function () {
  15841. behavior.attach(_this);
  15842. setTimeout(function () {
  15843. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15844. _this._scene.onDataLoadedObservable.remove(observer);
  15845. }, 0);
  15846. });
  15847. }
  15848. else {
  15849. behavior.attach(this);
  15850. }
  15851. this._behaviors.push(behavior);
  15852. return this;
  15853. };
  15854. /**
  15855. * Remove an attached behavior
  15856. * @see http://doc.babylonjs.com/features/behaviour
  15857. * @param behavior defines the behavior to attach
  15858. * @returns the current Node
  15859. */
  15860. Node.prototype.removeBehavior = function (behavior) {
  15861. var index = this._behaviors.indexOf(behavior);
  15862. if (index === -1) {
  15863. return this;
  15864. }
  15865. this._behaviors[index].detach();
  15866. this._behaviors.splice(index, 1);
  15867. return this;
  15868. };
  15869. Object.defineProperty(Node.prototype, "behaviors", {
  15870. /**
  15871. * Gets the list of attached behaviors
  15872. * @see http://doc.babylonjs.com/features/behaviour
  15873. */
  15874. get: function () {
  15875. return this._behaviors;
  15876. },
  15877. enumerable: true,
  15878. configurable: true
  15879. });
  15880. /**
  15881. * Gets an attached behavior by name
  15882. * @param name defines the name of the behavior to look for
  15883. * @see http://doc.babylonjs.com/features/behaviour
  15884. * @returns null if behavior was not found else the requested behavior
  15885. */
  15886. Node.prototype.getBehaviorByName = function (name) {
  15887. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15888. var behavior = _a[_i];
  15889. if (behavior.name === name) {
  15890. return behavior;
  15891. }
  15892. }
  15893. return null;
  15894. };
  15895. /**
  15896. * Returns the world matrix of the node
  15897. * @returns a matrix containing the node's world matrix
  15898. */
  15899. Node.prototype.getWorldMatrix = function () {
  15900. return BABYLON.Matrix.Identity();
  15901. };
  15902. // override it in derived class if you add new variables to the cache
  15903. // and call the parent class method
  15904. /** @ignore */
  15905. Node.prototype._initCache = function () {
  15906. this._cache = {};
  15907. this._cache.parent = undefined;
  15908. };
  15909. /** @ignore */
  15910. Node.prototype.updateCache = function (force) {
  15911. if (!force && this.isSynchronized())
  15912. return;
  15913. this._cache.parent = this.parent;
  15914. this._updateCache();
  15915. };
  15916. // override it in derived class if you add new variables to the cache
  15917. // and call the parent class method if !ignoreParentClass
  15918. /** @ignore */
  15919. Node.prototype._updateCache = function (ignoreParentClass) {
  15920. };
  15921. // override it in derived class if you add new variables to the cache
  15922. /** @ignore */
  15923. Node.prototype._isSynchronized = function () {
  15924. return true;
  15925. };
  15926. /** @ignore */
  15927. Node.prototype._markSyncedWithParent = function () {
  15928. if (this.parent) {
  15929. this._parentRenderId = this.parent._currentRenderId;
  15930. }
  15931. };
  15932. /** @ignore */
  15933. Node.prototype.isSynchronizedWithParent = function () {
  15934. if (!this.parent) {
  15935. return true;
  15936. }
  15937. if (this._parentRenderId !== this.parent._currentRenderId) {
  15938. return false;
  15939. }
  15940. return this.parent.isSynchronized();
  15941. };
  15942. /** @ignore */
  15943. Node.prototype.isSynchronized = function (updateCache) {
  15944. var check = this.hasNewParent();
  15945. check = check || !this.isSynchronizedWithParent();
  15946. check = check || !this._isSynchronized();
  15947. if (updateCache)
  15948. this.updateCache(true);
  15949. return !check;
  15950. };
  15951. /** @ignore */
  15952. Node.prototype.hasNewParent = function (update) {
  15953. if (this._cache.parent === this.parent)
  15954. return false;
  15955. if (update)
  15956. this._cache.parent = this.parent;
  15957. return true;
  15958. };
  15959. /**
  15960. * Is this node ready to be used/rendered
  15961. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15962. * @return true if the node is ready
  15963. */
  15964. Node.prototype.isReady = function (completeCheck) {
  15965. if (completeCheck === void 0) { completeCheck = false; }
  15966. return this._isReady;
  15967. };
  15968. /**
  15969. * Is this node enabled?
  15970. * 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
  15971. * @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
  15972. * @return whether this node (and its parent) is enabled
  15973. * @see setEnabled
  15974. */
  15975. Node.prototype.isEnabled = function (checkAncestors) {
  15976. if (checkAncestors === void 0) { checkAncestors = true; }
  15977. if (checkAncestors === false) {
  15978. return this._isEnabled;
  15979. }
  15980. if (this._isEnabled === false) {
  15981. return false;
  15982. }
  15983. if (this.parent !== undefined && this.parent !== null) {
  15984. return this.parent.isEnabled(checkAncestors);
  15985. }
  15986. return true;
  15987. };
  15988. /**
  15989. * Set the enabled state of this node
  15990. * @param value defines the new enabled state
  15991. * @see isEnabled
  15992. */
  15993. Node.prototype.setEnabled = function (value) {
  15994. this._isEnabled = value;
  15995. };
  15996. /**
  15997. * Is this node a descendant of the given node?
  15998. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15999. * @param ancestor defines the parent node to inspect
  16000. * @see parent
  16001. * @returns a boolean indicating if this node is a descendant of the given node
  16002. */
  16003. Node.prototype.isDescendantOf = function (ancestor) {
  16004. if (this.parent) {
  16005. if (this.parent === ancestor) {
  16006. return true;
  16007. }
  16008. return this.parent.isDescendantOf(ancestor);
  16009. }
  16010. return false;
  16011. };
  16012. /** @ignore */
  16013. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  16014. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  16015. if (!this._children) {
  16016. return;
  16017. }
  16018. for (var index = 0; index < this._children.length; index++) {
  16019. var item = this._children[index];
  16020. if (!predicate || predicate(item)) {
  16021. results.push(item);
  16022. }
  16023. if (!directDescendantsOnly) {
  16024. item._getDescendants(results, false, predicate);
  16025. }
  16026. }
  16027. };
  16028. /**
  16029. * Will return all nodes that have this node as ascendant
  16030. * @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
  16031. * @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
  16032. * @return all children nodes of all types
  16033. */
  16034. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  16035. var results = new Array();
  16036. this._getDescendants(results, directDescendantsOnly, predicate);
  16037. return results;
  16038. };
  16039. /**
  16040. * Get all child-meshes of this node
  16041. * @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
  16042. * @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
  16043. * @returns an array of {BABYLON.AbstractMesh}
  16044. */
  16045. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  16046. var results = [];
  16047. this._getDescendants(results, directDescendantsOnly, function (node) {
  16048. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  16049. });
  16050. return results;
  16051. };
  16052. /**
  16053. * Get all child-transformNodes of this node
  16054. * @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
  16055. * @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
  16056. * @returns an array of {BABYLON.TransformNode}
  16057. */
  16058. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  16059. var results = [];
  16060. this._getDescendants(results, directDescendantsOnly, function (node) {
  16061. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16062. });
  16063. return results;
  16064. };
  16065. /**
  16066. * Get all direct children of this node
  16067. * @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
  16068. * @returns an array of {BABYLON.Node}
  16069. */
  16070. Node.prototype.getChildren = function (predicate) {
  16071. return this.getDescendants(true, predicate);
  16072. };
  16073. /** @ignore */
  16074. Node.prototype._setReady = function (state) {
  16075. if (state === this._isReady) {
  16076. return;
  16077. }
  16078. if (!state) {
  16079. this._isReady = false;
  16080. return;
  16081. }
  16082. if (this.onReady) {
  16083. this.onReady(this);
  16084. }
  16085. this._isReady = true;
  16086. };
  16087. /**
  16088. * Get an animation by name
  16089. * @param name defines the name of the animation to look for
  16090. * @returns null if not found else the requested animation
  16091. */
  16092. Node.prototype.getAnimationByName = function (name) {
  16093. for (var i = 0; i < this.animations.length; i++) {
  16094. var animation = this.animations[i];
  16095. if (animation.name === name) {
  16096. return animation;
  16097. }
  16098. }
  16099. return null;
  16100. };
  16101. /**
  16102. * Creates an animation range for this node
  16103. * @param name defines the name of the range
  16104. * @param from defines the starting key
  16105. * @param to defines the end key
  16106. */
  16107. Node.prototype.createAnimationRange = function (name, from, to) {
  16108. // check name not already in use
  16109. if (!this._ranges[name]) {
  16110. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16111. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16112. if (this.animations[i]) {
  16113. this.animations[i].createRange(name, from, to);
  16114. }
  16115. }
  16116. }
  16117. };
  16118. /**
  16119. * Delete a specific animation range
  16120. * @param name defines the name of the range to delete
  16121. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16122. */
  16123. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16124. if (deleteFrames === void 0) { deleteFrames = true; }
  16125. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16126. if (this.animations[i]) {
  16127. this.animations[i].deleteRange(name, deleteFrames);
  16128. }
  16129. }
  16130. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16131. };
  16132. /**
  16133. * Get an animation range by name
  16134. * @param name defines the name of the animation range to look for
  16135. * @returns null if not found else the requested animation range
  16136. */
  16137. Node.prototype.getAnimationRange = function (name) {
  16138. return this._ranges[name];
  16139. };
  16140. /**
  16141. * Will start the animation sequence
  16142. * @param name defines the range frames for animation sequence
  16143. * @param loop defines if the animation should loop (false by default)
  16144. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16145. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16146. * @returns the object created for this animation. If range does not exist, it will return null
  16147. */
  16148. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16149. var range = this.getAnimationRange(name);
  16150. if (!range) {
  16151. return null;
  16152. }
  16153. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16154. };
  16155. /**
  16156. * Serialize animation ranges into a JSON compatible object
  16157. * @returns serialization object
  16158. */
  16159. Node.prototype.serializeAnimationRanges = function () {
  16160. var serializationRanges = [];
  16161. for (var name in this._ranges) {
  16162. var localRange = this._ranges[name];
  16163. if (!localRange) {
  16164. continue;
  16165. }
  16166. var range = {};
  16167. range.name = name;
  16168. range.from = localRange.from;
  16169. range.to = localRange.to;
  16170. serializationRanges.push(range);
  16171. }
  16172. return serializationRanges;
  16173. };
  16174. /**
  16175. * Computes the world matrix of the node
  16176. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16177. * @returns the world matrix
  16178. */
  16179. Node.prototype.computeWorldMatrix = function (force) {
  16180. return BABYLON.Matrix.Identity();
  16181. };
  16182. /**
  16183. * Releases resources associated with this node.
  16184. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16185. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16186. */
  16187. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16188. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16189. if (!doNotRecurse) {
  16190. var nodes = this.getDescendants(true);
  16191. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16192. var node = nodes_1[_i];
  16193. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16194. }
  16195. }
  16196. else {
  16197. var transformNodes = this.getChildTransformNodes(true);
  16198. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16199. var transformNode = transformNodes_1[_a];
  16200. transformNode.parent = null;
  16201. transformNode.computeWorldMatrix(true);
  16202. }
  16203. }
  16204. this.parent = null;
  16205. // Callback
  16206. this.onDisposeObservable.notifyObservers(this);
  16207. this.onDisposeObservable.clear();
  16208. // Behaviors
  16209. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16210. var behavior = _c[_b];
  16211. behavior.detach();
  16212. }
  16213. this._behaviors = [];
  16214. this._isDisposed = true;
  16215. };
  16216. /**
  16217. * Parse animation range data from a serialization object and store them into a given node
  16218. * @param node defines where to store the animation ranges
  16219. * @param parsedNode defines the serialization object to read data from
  16220. * @param scene defines the hosting scene
  16221. */
  16222. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16223. if (parsedNode.ranges) {
  16224. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16225. var data = parsedNode.ranges[index];
  16226. node.createAnimationRange(data.name, data.from, data.to);
  16227. }
  16228. }
  16229. };
  16230. __decorate([
  16231. BABYLON.serialize()
  16232. ], Node.prototype, "name", void 0);
  16233. __decorate([
  16234. BABYLON.serialize()
  16235. ], Node.prototype, "id", void 0);
  16236. __decorate([
  16237. BABYLON.serialize()
  16238. ], Node.prototype, "uniqueId", void 0);
  16239. __decorate([
  16240. BABYLON.serialize()
  16241. ], Node.prototype, "state", void 0);
  16242. __decorate([
  16243. BABYLON.serialize()
  16244. ], Node.prototype, "metadata", void 0);
  16245. return Node;
  16246. }());
  16247. BABYLON.Node = Node;
  16248. })(BABYLON || (BABYLON = {}));
  16249. //# sourceMappingURL=babylon.node.js.map
  16250. "use strict";
  16251. var BABYLON;
  16252. (function (BABYLON) {
  16253. var BoundingSphere = /** @class */ (function () {
  16254. function BoundingSphere(minimum, maximum) {
  16255. this.minimum = minimum;
  16256. this.maximum = maximum;
  16257. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16258. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16259. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16260. this.radius = distance * 0.5;
  16261. this.centerWorld = BABYLON.Vector3.Zero();
  16262. this._update(BABYLON.Matrix.Identity());
  16263. }
  16264. // Methods
  16265. BoundingSphere.prototype._update = function (world) {
  16266. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16267. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16268. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16269. };
  16270. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16271. for (var i = 0; i < 6; i++) {
  16272. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16273. return false;
  16274. }
  16275. return true;
  16276. };
  16277. BoundingSphere.prototype.intersectsPoint = function (point) {
  16278. var x = this.centerWorld.x - point.x;
  16279. var y = this.centerWorld.y - point.y;
  16280. var z = this.centerWorld.z - point.z;
  16281. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16282. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16283. return false;
  16284. return true;
  16285. };
  16286. // Statics
  16287. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16288. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16289. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16290. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16291. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16292. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16293. return false;
  16294. return true;
  16295. };
  16296. return BoundingSphere;
  16297. }());
  16298. BABYLON.BoundingSphere = BoundingSphere;
  16299. })(BABYLON || (BABYLON = {}));
  16300. //# sourceMappingURL=babylon.boundingSphere.js.map
  16301. "use strict";
  16302. var BABYLON;
  16303. (function (BABYLON) {
  16304. var BoundingBox = /** @class */ (function () {
  16305. function BoundingBox(minimum, maximum) {
  16306. this.minimum = minimum;
  16307. this.maximum = maximum;
  16308. this.vectors = new Array();
  16309. this.vectorsWorld = new Array();
  16310. // Bounding vectors
  16311. this.vectors.push(this.minimum.clone());
  16312. this.vectors.push(this.maximum.clone());
  16313. this.vectors.push(this.minimum.clone());
  16314. this.vectors[2].x = this.maximum.x;
  16315. this.vectors.push(this.minimum.clone());
  16316. this.vectors[3].y = this.maximum.y;
  16317. this.vectors.push(this.minimum.clone());
  16318. this.vectors[4].z = this.maximum.z;
  16319. this.vectors.push(this.maximum.clone());
  16320. this.vectors[5].z = this.minimum.z;
  16321. this.vectors.push(this.maximum.clone());
  16322. this.vectors[6].x = this.minimum.x;
  16323. this.vectors.push(this.maximum.clone());
  16324. this.vectors[7].y = this.minimum.y;
  16325. // OBB
  16326. this.center = this.maximum.add(this.minimum).scale(0.5);
  16327. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16328. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16329. // World
  16330. for (var index = 0; index < this.vectors.length; index++) {
  16331. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16332. }
  16333. this.minimumWorld = BABYLON.Vector3.Zero();
  16334. this.maximumWorld = BABYLON.Vector3.Zero();
  16335. this.centerWorld = BABYLON.Vector3.Zero();
  16336. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16337. this._update(BABYLON.Matrix.Identity());
  16338. }
  16339. // Methods
  16340. BoundingBox.prototype.getWorldMatrix = function () {
  16341. return this._worldMatrix;
  16342. };
  16343. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16344. this._worldMatrix.copyFrom(matrix);
  16345. return this;
  16346. };
  16347. BoundingBox.prototype._update = function (world) {
  16348. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16349. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16350. for (var index = 0; index < this.vectors.length; index++) {
  16351. var v = this.vectorsWorld[index];
  16352. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16353. if (v.x < this.minimumWorld.x)
  16354. this.minimumWorld.x = v.x;
  16355. if (v.y < this.minimumWorld.y)
  16356. this.minimumWorld.y = v.y;
  16357. if (v.z < this.minimumWorld.z)
  16358. this.minimumWorld.z = v.z;
  16359. if (v.x > this.maximumWorld.x)
  16360. this.maximumWorld.x = v.x;
  16361. if (v.y > this.maximumWorld.y)
  16362. this.maximumWorld.y = v.y;
  16363. if (v.z > this.maximumWorld.z)
  16364. this.maximumWorld.z = v.z;
  16365. }
  16366. // Extend
  16367. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16368. this.extendSizeWorld.scaleInPlace(0.5);
  16369. // OBB
  16370. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16371. this.centerWorld.scaleInPlace(0.5);
  16372. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16373. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16374. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16375. this._worldMatrix = world;
  16376. };
  16377. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16378. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16379. };
  16380. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16381. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16382. };
  16383. BoundingBox.prototype.intersectsPoint = function (point) {
  16384. var delta = -BABYLON.Epsilon;
  16385. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16386. return false;
  16387. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16388. return false;
  16389. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16390. return false;
  16391. return true;
  16392. };
  16393. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16394. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16395. };
  16396. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16397. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16398. return false;
  16399. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16400. return false;
  16401. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16402. return false;
  16403. return true;
  16404. };
  16405. // Statics
  16406. BoundingBox.Intersects = function (box0, box1) {
  16407. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16408. return false;
  16409. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16410. return false;
  16411. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16412. return false;
  16413. return true;
  16414. };
  16415. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16416. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16417. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16418. return (num <= (sphereRadius * sphereRadius));
  16419. };
  16420. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16421. for (var p = 0; p < 6; p++) {
  16422. for (var i = 0; i < 8; i++) {
  16423. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16424. return false;
  16425. }
  16426. }
  16427. }
  16428. return true;
  16429. };
  16430. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16431. for (var p = 0; p < 6; p++) {
  16432. var inCount = 8;
  16433. for (var i = 0; i < 8; i++) {
  16434. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16435. --inCount;
  16436. }
  16437. else {
  16438. break;
  16439. }
  16440. }
  16441. if (inCount === 0)
  16442. return false;
  16443. }
  16444. return true;
  16445. };
  16446. return BoundingBox;
  16447. }());
  16448. BABYLON.BoundingBox = BoundingBox;
  16449. })(BABYLON || (BABYLON = {}));
  16450. //# sourceMappingURL=babylon.boundingBox.js.map
  16451. "use strict";
  16452. var BABYLON;
  16453. (function (BABYLON) {
  16454. var computeBoxExtents = function (axis, box) {
  16455. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16456. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16457. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16458. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16459. var r = r0 + r1 + r2;
  16460. return {
  16461. min: p - r,
  16462. max: p + r
  16463. };
  16464. };
  16465. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16466. var axisOverlap = function (axis, box0, box1) {
  16467. var result0 = computeBoxExtents(axis, box0);
  16468. var result1 = computeBoxExtents(axis, box1);
  16469. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16470. };
  16471. var BoundingInfo = /** @class */ (function () {
  16472. function BoundingInfo(minimum, maximum) {
  16473. this.minimum = minimum;
  16474. this.maximum = maximum;
  16475. this._isLocked = false;
  16476. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16477. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16478. }
  16479. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16480. get: function () {
  16481. return this._isLocked;
  16482. },
  16483. set: function (value) {
  16484. this._isLocked = value;
  16485. },
  16486. enumerable: true,
  16487. configurable: true
  16488. });
  16489. // Methods
  16490. BoundingInfo.prototype.update = function (world) {
  16491. if (this._isLocked) {
  16492. return;
  16493. }
  16494. this.boundingBox._update(world);
  16495. this.boundingSphere._update(world);
  16496. };
  16497. /**
  16498. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16499. * @param center New center of the bounding info
  16500. * @param extend New extend of the bounding info
  16501. */
  16502. BoundingInfo.prototype.centerOn = function (center, extend) {
  16503. this.minimum = center.subtract(extend);
  16504. this.maximum = center.add(extend);
  16505. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16506. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16507. return this;
  16508. };
  16509. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16510. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16511. return false;
  16512. return this.boundingBox.isInFrustum(frustumPlanes);
  16513. };
  16514. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16515. /**
  16516. * Gets the world distance between the min and max points of the bounding box
  16517. */
  16518. get: function () {
  16519. var boundingBox = this.boundingBox;
  16520. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16521. return size.length();
  16522. },
  16523. enumerable: true,
  16524. configurable: true
  16525. });
  16526. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16527. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16528. };
  16529. BoundingInfo.prototype._checkCollision = function (collider) {
  16530. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16531. };
  16532. BoundingInfo.prototype.intersectsPoint = function (point) {
  16533. if (!this.boundingSphere.centerWorld) {
  16534. return false;
  16535. }
  16536. if (!this.boundingSphere.intersectsPoint(point)) {
  16537. return false;
  16538. }
  16539. if (!this.boundingBox.intersectsPoint(point)) {
  16540. return false;
  16541. }
  16542. return true;
  16543. };
  16544. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16545. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16546. return false;
  16547. }
  16548. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16549. return false;
  16550. }
  16551. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16552. return false;
  16553. }
  16554. if (!precise) {
  16555. return true;
  16556. }
  16557. var box0 = this.boundingBox;
  16558. var box1 = boundingInfo.boundingBox;
  16559. if (!axisOverlap(box0.directions[0], box0, box1))
  16560. return false;
  16561. if (!axisOverlap(box0.directions[1], box0, box1))
  16562. return false;
  16563. if (!axisOverlap(box0.directions[2], box0, box1))
  16564. return false;
  16565. if (!axisOverlap(box1.directions[0], box0, box1))
  16566. return false;
  16567. if (!axisOverlap(box1.directions[1], box0, box1))
  16568. return false;
  16569. if (!axisOverlap(box1.directions[2], box0, box1))
  16570. return false;
  16571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16572. return false;
  16573. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16574. return false;
  16575. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16576. return false;
  16577. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16578. return false;
  16579. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16580. return false;
  16581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16582. return false;
  16583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16584. return false;
  16585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16586. return false;
  16587. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16588. return false;
  16589. return true;
  16590. };
  16591. return BoundingInfo;
  16592. }());
  16593. BABYLON.BoundingInfo = BoundingInfo;
  16594. })(BABYLON || (BABYLON = {}));
  16595. //# sourceMappingURL=babylon.boundingInfo.js.map
  16596. "use strict";
  16597. var BABYLON;
  16598. (function (BABYLON) {
  16599. var TransformNode = /** @class */ (function (_super) {
  16600. __extends(TransformNode, _super);
  16601. function TransformNode(name, scene, isPure) {
  16602. if (scene === void 0) { scene = null; }
  16603. if (isPure === void 0) { isPure = true; }
  16604. var _this = _super.call(this, name, scene) || this;
  16605. // Properties
  16606. _this._rotation = BABYLON.Vector3.Zero();
  16607. _this._scaling = BABYLON.Vector3.One();
  16608. _this._isDirty = false;
  16609. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16610. _this.scalingDeterminant = 1;
  16611. _this.infiniteDistance = false;
  16612. _this.position = BABYLON.Vector3.Zero();
  16613. _this._localWorld = BABYLON.Matrix.Zero();
  16614. _this._worldMatrix = BABYLON.Matrix.Zero();
  16615. _this._worldMatrixDeterminant = 0;
  16616. _this._absolutePosition = BABYLON.Vector3.Zero();
  16617. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16618. _this._postMultiplyPivotMatrix = false;
  16619. _this._isWorldMatrixFrozen = false;
  16620. /**
  16621. * An event triggered after the world matrix is updated
  16622. * @type {BABYLON.Observable}
  16623. */
  16624. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16625. _this._nonUniformScaling = false;
  16626. if (isPure) {
  16627. _this.getScene().addTransformNode(_this);
  16628. }
  16629. return _this;
  16630. }
  16631. /**
  16632. * Gets a string idenfifying the name of the class
  16633. * @returns "TransformNode" string
  16634. */
  16635. TransformNode.prototype.getClassName = function () {
  16636. return "TransformNode";
  16637. };
  16638. Object.defineProperty(TransformNode.prototype, "rotation", {
  16639. /**
  16640. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16641. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16642. * Default : (0.0, 0.0, 0.0)
  16643. */
  16644. get: function () {
  16645. return this._rotation;
  16646. },
  16647. set: function (newRotation) {
  16648. this._rotation = newRotation;
  16649. },
  16650. enumerable: true,
  16651. configurable: true
  16652. });
  16653. Object.defineProperty(TransformNode.prototype, "scaling", {
  16654. /**
  16655. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16656. * Default : (1.0, 1.0, 1.0)
  16657. */
  16658. get: function () {
  16659. return this._scaling;
  16660. },
  16661. /**
  16662. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16663. * Default : (1.0, 1.0, 1.0)
  16664. */
  16665. set: function (newScaling) {
  16666. this._scaling = newScaling;
  16667. },
  16668. enumerable: true,
  16669. configurable: true
  16670. });
  16671. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16672. /**
  16673. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16674. * It's null by default.
  16675. * 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)
  16676. */
  16677. get: function () {
  16678. return this._rotationQuaternion;
  16679. },
  16680. set: function (quaternion) {
  16681. this._rotationQuaternion = quaternion;
  16682. //reset the rotation vector.
  16683. if (quaternion && this.rotation.length()) {
  16684. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16685. }
  16686. },
  16687. enumerable: true,
  16688. configurable: true
  16689. });
  16690. /**
  16691. * Returns the latest update of the World matrix
  16692. * Returns a Matrix.
  16693. */
  16694. TransformNode.prototype.getWorldMatrix = function () {
  16695. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16696. this.computeWorldMatrix();
  16697. }
  16698. return this._worldMatrix;
  16699. };
  16700. /**
  16701. * Returns the latest update of the World matrix determinant.
  16702. */
  16703. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16704. return this._worldMatrixDeterminant;
  16705. };
  16706. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16707. /**
  16708. * Returns directly the latest state of the mesh World matrix.
  16709. * A Matrix is returned.
  16710. */
  16711. get: function () {
  16712. return this._worldMatrix;
  16713. },
  16714. enumerable: true,
  16715. configurable: true
  16716. });
  16717. /**
  16718. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16719. * Returns the AbstractMesh.
  16720. */
  16721. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16722. this._poseMatrix.copyFrom(matrix);
  16723. return this;
  16724. };
  16725. /**
  16726. * Returns the mesh Pose matrix.
  16727. * Returned object : Matrix
  16728. */
  16729. TransformNode.prototype.getPoseMatrix = function () {
  16730. return this._poseMatrix;
  16731. };
  16732. TransformNode.prototype._isSynchronized = function () {
  16733. if (this._isDirty) {
  16734. return false;
  16735. }
  16736. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16737. return false;
  16738. if (this._cache.pivotMatrixUpdated) {
  16739. return false;
  16740. }
  16741. if (this.infiniteDistance) {
  16742. return false;
  16743. }
  16744. if (!this._cache.position.equals(this.position))
  16745. return false;
  16746. if (this.rotationQuaternion) {
  16747. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16748. return false;
  16749. }
  16750. if (!this._cache.rotation.equals(this.rotation))
  16751. return false;
  16752. if (!this._cache.scaling.equals(this.scaling))
  16753. return false;
  16754. return true;
  16755. };
  16756. TransformNode.prototype._initCache = function () {
  16757. _super.prototype._initCache.call(this);
  16758. this._cache.localMatrixUpdated = false;
  16759. this._cache.position = BABYLON.Vector3.Zero();
  16760. this._cache.scaling = BABYLON.Vector3.Zero();
  16761. this._cache.rotation = BABYLON.Vector3.Zero();
  16762. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16763. this._cache.billboardMode = -1;
  16764. };
  16765. TransformNode.prototype.markAsDirty = function (property) {
  16766. if (property === "rotation") {
  16767. this.rotationQuaternion = null;
  16768. }
  16769. this._currentRenderId = Number.MAX_VALUE;
  16770. this._isDirty = true;
  16771. return this;
  16772. };
  16773. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16774. /**
  16775. * Returns the current mesh absolute position.
  16776. * Retuns a Vector3.
  16777. */
  16778. get: function () {
  16779. return this._absolutePosition;
  16780. },
  16781. enumerable: true,
  16782. configurable: true
  16783. });
  16784. /**
  16785. * Sets a new matrix to apply before all other transformation
  16786. * @param matrix defines the transform matrix
  16787. * @returns the current TransformNode
  16788. */
  16789. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16790. return this.setPivotMatrix(matrix, false);
  16791. };
  16792. /**
  16793. * Sets a new pivot matrix to the current node
  16794. * @param matrix defines the new pivot matrix to use
  16795. * @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
  16796. * @returns the current TransformNode
  16797. */
  16798. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16799. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16800. this._pivotMatrix = matrix.clone();
  16801. this._cache.pivotMatrixUpdated = true;
  16802. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16803. if (this._postMultiplyPivotMatrix) {
  16804. if (!this._pivotMatrixInverse) {
  16805. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16806. }
  16807. else {
  16808. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16809. }
  16810. }
  16811. return this;
  16812. };
  16813. /**
  16814. * Returns the mesh pivot matrix.
  16815. * Default : Identity.
  16816. * A Matrix is returned.
  16817. */
  16818. TransformNode.prototype.getPivotMatrix = function () {
  16819. return this._pivotMatrix;
  16820. };
  16821. /**
  16822. * Prevents the World matrix to be computed any longer.
  16823. * Returns the AbstractMesh.
  16824. */
  16825. TransformNode.prototype.freezeWorldMatrix = function () {
  16826. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16827. this.computeWorldMatrix(true);
  16828. this._isWorldMatrixFrozen = true;
  16829. return this;
  16830. };
  16831. /**
  16832. * Allows back the World matrix computation.
  16833. * Returns the AbstractMesh.
  16834. */
  16835. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16836. this._isWorldMatrixFrozen = false;
  16837. this.computeWorldMatrix(true);
  16838. return this;
  16839. };
  16840. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16841. /**
  16842. * True if the World matrix has been frozen.
  16843. * Returns a boolean.
  16844. */
  16845. get: function () {
  16846. return this._isWorldMatrixFrozen;
  16847. },
  16848. enumerable: true,
  16849. configurable: true
  16850. });
  16851. /**
  16852. * Retuns the mesh absolute position in the World.
  16853. * Returns a Vector3.
  16854. */
  16855. TransformNode.prototype.getAbsolutePosition = function () {
  16856. this.computeWorldMatrix();
  16857. return this._absolutePosition;
  16858. };
  16859. /**
  16860. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16861. * Returns the AbstractMesh.
  16862. */
  16863. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16864. if (!absolutePosition) {
  16865. return this;
  16866. }
  16867. var absolutePositionX;
  16868. var absolutePositionY;
  16869. var absolutePositionZ;
  16870. if (absolutePosition.x === undefined) {
  16871. if (arguments.length < 3) {
  16872. return this;
  16873. }
  16874. absolutePositionX = arguments[0];
  16875. absolutePositionY = arguments[1];
  16876. absolutePositionZ = arguments[2];
  16877. }
  16878. else {
  16879. absolutePositionX = absolutePosition.x;
  16880. absolutePositionY = absolutePosition.y;
  16881. absolutePositionZ = absolutePosition.z;
  16882. }
  16883. if (this.parent) {
  16884. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16885. invertParentWorldMatrix.invert();
  16886. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16887. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16888. }
  16889. else {
  16890. this.position.x = absolutePositionX;
  16891. this.position.y = absolutePositionY;
  16892. this.position.z = absolutePositionZ;
  16893. }
  16894. return this;
  16895. };
  16896. /**
  16897. * Sets the mesh position in its local space.
  16898. * Returns the AbstractMesh.
  16899. */
  16900. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16901. this.computeWorldMatrix();
  16902. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16903. return this;
  16904. };
  16905. /**
  16906. * Returns the mesh position in the local space from the current World matrix values.
  16907. * Returns a new Vector3.
  16908. */
  16909. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16910. this.computeWorldMatrix();
  16911. var invLocalWorldMatrix = this._localWorld.clone();
  16912. invLocalWorldMatrix.invert();
  16913. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16914. };
  16915. /**
  16916. * Translates the mesh along the passed Vector3 in its local space.
  16917. * Returns the AbstractMesh.
  16918. */
  16919. TransformNode.prototype.locallyTranslate = function (vector3) {
  16920. this.computeWorldMatrix(true);
  16921. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16922. return this;
  16923. };
  16924. /**
  16925. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16926. * @param targetPoint the position (must be in same space as current mesh) to look at
  16927. * @param yawCor optional yaw (y-axis) correction in radians
  16928. * @param pitchCor optional pitch (x-axis) correction in radians
  16929. * @param rollCor optional roll (z-axis) correction in radians
  16930. * @param space the choosen space of the target
  16931. * @returns the TransformNode.
  16932. */
  16933. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16934. if (yawCor === void 0) { yawCor = 0; }
  16935. if (pitchCor === void 0) { pitchCor = 0; }
  16936. if (rollCor === void 0) { rollCor = 0; }
  16937. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16938. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16939. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16940. targetPoint.subtractToRef(pos, dv);
  16941. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16942. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16943. var pitch = Math.atan2(dv.y, len);
  16944. if (this.rotationQuaternion) {
  16945. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16946. }
  16947. else {
  16948. this.rotation.x = pitch + pitchCor;
  16949. this.rotation.y = yaw + yawCor;
  16950. this.rotation.z = rollCor;
  16951. }
  16952. return this;
  16953. };
  16954. /**
  16955. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16956. * This Vector3 is expressed in the World space.
  16957. */
  16958. TransformNode.prototype.getDirection = function (localAxis) {
  16959. var result = BABYLON.Vector3.Zero();
  16960. this.getDirectionToRef(localAxis, result);
  16961. return result;
  16962. };
  16963. /**
  16964. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16965. * localAxis is expressed in the mesh local space.
  16966. * result is computed in the Wordl space from the mesh World matrix.
  16967. * Returns the AbstractMesh.
  16968. */
  16969. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16970. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16971. return this;
  16972. };
  16973. /**
  16974. * Sets a new pivot point to the current node
  16975. * @param point defines the new pivot point to use
  16976. * @param space defines if the point is in world or local space (local by default)
  16977. * @returns the current TransformNode
  16978. */
  16979. TransformNode.prototype.setPivotPoint = function (point, space) {
  16980. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16981. if (this.getScene().getRenderId() == 0) {
  16982. this.computeWorldMatrix(true);
  16983. }
  16984. var wm = this.getWorldMatrix();
  16985. if (space == BABYLON.Space.WORLD) {
  16986. var tmat = BABYLON.Tmp.Matrix[0];
  16987. wm.invertToRef(tmat);
  16988. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16989. }
  16990. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16991. };
  16992. /**
  16993. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16994. */
  16995. TransformNode.prototype.getPivotPoint = function () {
  16996. var point = BABYLON.Vector3.Zero();
  16997. this.getPivotPointToRef(point);
  16998. return point;
  16999. };
  17000. /**
  17001. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  17002. * Returns the AbstractMesh.
  17003. */
  17004. TransformNode.prototype.getPivotPointToRef = function (result) {
  17005. result.x = -this._pivotMatrix.m[12];
  17006. result.y = -this._pivotMatrix.m[13];
  17007. result.z = -this._pivotMatrix.m[14];
  17008. return this;
  17009. };
  17010. /**
  17011. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  17012. */
  17013. TransformNode.prototype.getAbsolutePivotPoint = function () {
  17014. var point = BABYLON.Vector3.Zero();
  17015. this.getAbsolutePivotPointToRef(point);
  17016. return point;
  17017. };
  17018. /**
  17019. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  17020. * Returns the AbstractMesh.
  17021. */
  17022. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  17023. result.x = this._pivotMatrix.m[12];
  17024. result.y = this._pivotMatrix.m[13];
  17025. result.z = this._pivotMatrix.m[14];
  17026. this.getPivotPointToRef(result);
  17027. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  17028. return this;
  17029. };
  17030. /**
  17031. * Defines the passed node as the parent of the current node.
  17032. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  17033. * Returns the TransformNode.
  17034. */
  17035. TransformNode.prototype.setParent = function (node) {
  17036. if (node === null) {
  17037. var rotation = BABYLON.Tmp.Quaternion[0];
  17038. var position = BABYLON.Tmp.Vector3[0];
  17039. var scale = BABYLON.Tmp.Vector3[1];
  17040. if (this.parent && this.parent.computeWorldMatrix) {
  17041. this.parent.computeWorldMatrix(true);
  17042. }
  17043. this.computeWorldMatrix(true);
  17044. this.getWorldMatrix().decompose(scale, rotation, position);
  17045. if (this.rotationQuaternion) {
  17046. this.rotationQuaternion.copyFrom(rotation);
  17047. }
  17048. else {
  17049. rotation.toEulerAnglesToRef(this.rotation);
  17050. }
  17051. this.scaling.x = scale.x;
  17052. this.scaling.y = scale.y;
  17053. this.scaling.z = scale.z;
  17054. this.position.x = position.x;
  17055. this.position.y = position.y;
  17056. this.position.z = position.z;
  17057. }
  17058. else {
  17059. var rotation = BABYLON.Tmp.Quaternion[0];
  17060. var position = BABYLON.Tmp.Vector3[0];
  17061. var scale = BABYLON.Tmp.Vector3[1];
  17062. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17063. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17064. this.computeWorldMatrix(true);
  17065. node.computeWorldMatrix(true);
  17066. node.getWorldMatrix().invertToRef(invParentMatrix);
  17067. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17068. diffMatrix.decompose(scale, rotation, position);
  17069. if (this.rotationQuaternion) {
  17070. this.rotationQuaternion.copyFrom(rotation);
  17071. }
  17072. else {
  17073. rotation.toEulerAnglesToRef(this.rotation);
  17074. }
  17075. this.position.x = position.x;
  17076. this.position.y = position.y;
  17077. this.position.z = position.z;
  17078. this.scaling.x = scale.x;
  17079. this.scaling.y = scale.y;
  17080. this.scaling.z = scale.z;
  17081. }
  17082. this.parent = node;
  17083. return this;
  17084. };
  17085. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17086. get: function () {
  17087. return this._nonUniformScaling;
  17088. },
  17089. enumerable: true,
  17090. configurable: true
  17091. });
  17092. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17093. if (this._nonUniformScaling === value) {
  17094. return false;
  17095. }
  17096. this._nonUniformScaling = true;
  17097. return true;
  17098. };
  17099. /**
  17100. * Attach the current TransformNode to another TransformNode associated with a bone
  17101. * @param bone Bone affecting the TransformNode
  17102. * @param affectedTransformNode TransformNode associated with the bone
  17103. */
  17104. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17105. this._transformToBoneReferal = affectedTransformNode;
  17106. this.parent = bone;
  17107. if (bone.getWorldMatrix().determinant() < 0) {
  17108. this.scalingDeterminant *= -1;
  17109. }
  17110. return this;
  17111. };
  17112. TransformNode.prototype.detachFromBone = function () {
  17113. if (!this.parent) {
  17114. return this;
  17115. }
  17116. if (this.parent.getWorldMatrix().determinant() < 0) {
  17117. this.scalingDeterminant *= -1;
  17118. }
  17119. this._transformToBoneReferal = null;
  17120. this.parent = null;
  17121. return this;
  17122. };
  17123. /**
  17124. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17125. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17126. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17127. * The passed axis is also normalized.
  17128. * Returns the AbstractMesh.
  17129. */
  17130. TransformNode.prototype.rotate = function (axis, amount, space) {
  17131. axis.normalize();
  17132. if (!this.rotationQuaternion) {
  17133. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17134. this.rotation = BABYLON.Vector3.Zero();
  17135. }
  17136. var rotationQuaternion;
  17137. if (!space || space === BABYLON.Space.LOCAL) {
  17138. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17139. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17140. }
  17141. else {
  17142. if (this.parent) {
  17143. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17144. invertParentWorldMatrix.invert();
  17145. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17146. }
  17147. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17148. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17149. }
  17150. return this;
  17151. };
  17152. /**
  17153. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17154. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17155. * The passed axis is also normalized.
  17156. * Returns the AbstractMesh.
  17157. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17158. */
  17159. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17160. axis.normalize();
  17161. if (!this.rotationQuaternion) {
  17162. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17163. this.rotation.copyFromFloats(0, 0, 0);
  17164. }
  17165. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17166. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17167. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17168. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17169. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17170. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17171. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17172. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17173. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17174. return this;
  17175. };
  17176. /**
  17177. * Translates the mesh along the axis vector for the passed distance in the given space.
  17178. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17179. * Returns the AbstractMesh.
  17180. */
  17181. TransformNode.prototype.translate = function (axis, distance, space) {
  17182. var displacementVector = axis.scale(distance);
  17183. if (!space || space === BABYLON.Space.LOCAL) {
  17184. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17185. this.setPositionWithLocalVector(tempV3);
  17186. }
  17187. else {
  17188. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17189. }
  17190. return this;
  17191. };
  17192. /**
  17193. * Adds a rotation step to the mesh current rotation.
  17194. * x, y, z are Euler angles expressed in radians.
  17195. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17196. * This means this rotation is made in the mesh local space only.
  17197. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17198. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17199. * ```javascript
  17200. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17201. * ```
  17202. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17203. * 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.
  17204. * Returns the AbstractMesh.
  17205. */
  17206. TransformNode.prototype.addRotation = function (x, y, z) {
  17207. var rotationQuaternion;
  17208. if (this.rotationQuaternion) {
  17209. rotationQuaternion = this.rotationQuaternion;
  17210. }
  17211. else {
  17212. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17213. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17214. }
  17215. var accumulation = BABYLON.Tmp.Quaternion[0];
  17216. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17217. rotationQuaternion.multiplyInPlace(accumulation);
  17218. if (!this.rotationQuaternion) {
  17219. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17220. }
  17221. return this;
  17222. };
  17223. /**
  17224. * Computes the mesh World matrix and returns it.
  17225. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17226. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17227. * If the parameter `force`is set to `true`, the actual computation is done.
  17228. * Returns the mesh World Matrix.
  17229. */
  17230. TransformNode.prototype.computeWorldMatrix = function (force) {
  17231. if (this._isWorldMatrixFrozen) {
  17232. return this._worldMatrix;
  17233. }
  17234. if (!force && this.isSynchronized(true)) {
  17235. return this._worldMatrix;
  17236. }
  17237. this._cache.position.copyFrom(this.position);
  17238. this._cache.scaling.copyFrom(this.scaling);
  17239. this._cache.pivotMatrixUpdated = false;
  17240. this._cache.billboardMode = this.billboardMode;
  17241. this._currentRenderId = this.getScene().getRenderId();
  17242. this._isDirty = false;
  17243. // Scaling
  17244. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17245. // Rotation
  17246. //rotate, if quaternion is set and rotation was used
  17247. if (this.rotationQuaternion) {
  17248. var len = this.rotation.length();
  17249. if (len) {
  17250. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17251. this.rotation.copyFromFloats(0, 0, 0);
  17252. }
  17253. }
  17254. if (this.rotationQuaternion) {
  17255. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17256. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17257. }
  17258. else {
  17259. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17260. this._cache.rotation.copyFrom(this.rotation);
  17261. }
  17262. // Translation
  17263. var camera = this.getScene().activeCamera;
  17264. if (this.infiniteDistance && !this.parent && camera) {
  17265. var cameraWorldMatrix = camera.getWorldMatrix();
  17266. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17267. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17268. }
  17269. else {
  17270. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17271. }
  17272. // Composing transformations
  17273. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17274. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17275. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17276. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17277. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17278. // Need to decompose each rotation here
  17279. var currentPosition = BABYLON.Tmp.Vector3[3];
  17280. if (this.parent && this.parent.getWorldMatrix) {
  17281. if (this._transformToBoneReferal) {
  17282. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17283. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17284. }
  17285. else {
  17286. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17287. }
  17288. }
  17289. else {
  17290. currentPosition.copyFrom(this.position);
  17291. }
  17292. currentPosition.subtractInPlace(camera.globalPosition);
  17293. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17294. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17295. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17296. }
  17297. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17298. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17299. }
  17300. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17301. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17302. }
  17303. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17304. }
  17305. else {
  17306. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17307. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17308. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17309. }
  17310. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17311. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17312. }
  17313. // Local world
  17314. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17315. // Parent
  17316. if (this.parent && this.parent.getWorldMatrix) {
  17317. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17318. if (this._transformToBoneReferal) {
  17319. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17320. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17321. }
  17322. else {
  17323. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17324. }
  17325. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17326. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17327. this._worldMatrix.copyFrom(this._localWorld);
  17328. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17329. }
  17330. else {
  17331. if (this._transformToBoneReferal) {
  17332. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17333. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17334. }
  17335. else {
  17336. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17337. }
  17338. }
  17339. this._markSyncedWithParent();
  17340. }
  17341. else {
  17342. this._worldMatrix.copyFrom(this._localWorld);
  17343. }
  17344. // Post multiply inverse of pivotMatrix
  17345. if (this._postMultiplyPivotMatrix) {
  17346. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17347. }
  17348. // Normal matrix
  17349. if (this.scaling.isNonUniform) {
  17350. this._updateNonUniformScalingState(true);
  17351. }
  17352. else if (this.parent && this.parent._nonUniformScaling) {
  17353. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17354. }
  17355. else {
  17356. this._updateNonUniformScalingState(false);
  17357. }
  17358. this._afterComputeWorldMatrix();
  17359. // Absolute position
  17360. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17361. // Callbacks
  17362. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17363. if (!this._poseMatrix) {
  17364. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17365. }
  17366. // Cache the determinant
  17367. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17368. return this._worldMatrix;
  17369. };
  17370. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17371. };
  17372. /**
  17373. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17374. * @param func: callback function to add
  17375. *
  17376. * Returns the TransformNode.
  17377. */
  17378. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17379. this.onAfterWorldMatrixUpdateObservable.add(func);
  17380. return this;
  17381. };
  17382. /**
  17383. * Removes a registered callback function.
  17384. * Returns the TransformNode.
  17385. */
  17386. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17387. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17388. return this;
  17389. };
  17390. /**
  17391. * Clone the current transform node
  17392. * Returns the new transform node
  17393. * @param name Name of the new clone
  17394. * @param newParent New parent for the clone
  17395. * @param doNotCloneChildren Do not clone children hierarchy
  17396. */
  17397. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17398. var _this = this;
  17399. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17400. result.name = name;
  17401. result.id = name;
  17402. if (newParent) {
  17403. result.parent = newParent;
  17404. }
  17405. if (!doNotCloneChildren) {
  17406. // Children
  17407. var directDescendants = this.getDescendants(true);
  17408. for (var index = 0; index < directDescendants.length; index++) {
  17409. var child = directDescendants[index];
  17410. if (child.clone) {
  17411. child.clone(name + "." + child.name, result);
  17412. }
  17413. }
  17414. }
  17415. return result;
  17416. };
  17417. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17418. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17419. serializationObject.type = this.getClassName();
  17420. // Parent
  17421. if (this.parent) {
  17422. serializationObject.parentId = this.parent.id;
  17423. }
  17424. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17425. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17426. }
  17427. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17428. serializationObject.isEnabled = this.isEnabled();
  17429. // Parent
  17430. if (this.parent) {
  17431. serializationObject.parentId = this.parent.id;
  17432. }
  17433. return serializationObject;
  17434. };
  17435. // Statics
  17436. /**
  17437. * Returns a new TransformNode object parsed from the source provided.
  17438. * The parameter `parsedMesh` is the source.
  17439. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17440. */
  17441. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17442. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17443. if (BABYLON.Tags) {
  17444. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17445. }
  17446. if (parsedTransformNode.localMatrix) {
  17447. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17448. }
  17449. else if (parsedTransformNode.pivotMatrix) {
  17450. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17451. }
  17452. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17453. // Parent
  17454. if (parsedTransformNode.parentId) {
  17455. transformNode._waitingParentId = parsedTransformNode.parentId;
  17456. }
  17457. return transformNode;
  17458. };
  17459. /**
  17460. * Releases resources associated with this transform node.
  17461. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17462. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17463. */
  17464. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17465. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17466. // Animations
  17467. this.getScene().stopAnimation(this);
  17468. // Remove from scene
  17469. this.getScene().removeTransformNode(this);
  17470. this.onAfterWorldMatrixUpdateObservable.clear();
  17471. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17472. };
  17473. // Statics
  17474. TransformNode.BILLBOARDMODE_NONE = 0;
  17475. TransformNode.BILLBOARDMODE_X = 1;
  17476. TransformNode.BILLBOARDMODE_Y = 2;
  17477. TransformNode.BILLBOARDMODE_Z = 4;
  17478. TransformNode.BILLBOARDMODE_ALL = 7;
  17479. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17480. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17481. __decorate([
  17482. BABYLON.serializeAsVector3()
  17483. ], TransformNode.prototype, "_rotation", void 0);
  17484. __decorate([
  17485. BABYLON.serializeAsQuaternion()
  17486. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17487. __decorate([
  17488. BABYLON.serializeAsVector3()
  17489. ], TransformNode.prototype, "_scaling", void 0);
  17490. __decorate([
  17491. BABYLON.serialize()
  17492. ], TransformNode.prototype, "billboardMode", void 0);
  17493. __decorate([
  17494. BABYLON.serialize()
  17495. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17496. __decorate([
  17497. BABYLON.serialize()
  17498. ], TransformNode.prototype, "infiniteDistance", void 0);
  17499. __decorate([
  17500. BABYLON.serializeAsVector3()
  17501. ], TransformNode.prototype, "position", void 0);
  17502. return TransformNode;
  17503. }(BABYLON.Node));
  17504. BABYLON.TransformNode = TransformNode;
  17505. })(BABYLON || (BABYLON = {}));
  17506. //# sourceMappingURL=babylon.transformNode.js.map
  17507. "use strict";
  17508. var BABYLON;
  17509. (function (BABYLON) {
  17510. var AbstractMesh = /** @class */ (function (_super) {
  17511. __extends(AbstractMesh, _super);
  17512. // Constructor
  17513. function AbstractMesh(name, scene) {
  17514. if (scene === void 0) { scene = null; }
  17515. var _this = _super.call(this, name, scene, false) || this;
  17516. _this._facetNb = 0; // facet number
  17517. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17518. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17519. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17520. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17521. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17522. _this._subDiv = {
  17523. max: 1,
  17524. X: 1,
  17525. Y: 1,
  17526. Z: 1
  17527. };
  17528. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17529. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17530. // Events
  17531. /**
  17532. * An event triggered when this mesh collides with another one
  17533. * @type {BABYLON.Observable}
  17534. */
  17535. _this.onCollideObservable = new BABYLON.Observable();
  17536. /**
  17537. * An event triggered when the collision's position changes
  17538. * @type {BABYLON.Observable}
  17539. */
  17540. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17541. /**
  17542. * An event triggered when material is changed
  17543. * @type {BABYLON.Observable}
  17544. */
  17545. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17546. // Properties
  17547. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17548. /**
  17549. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17550. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17551. * or
  17552. * 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.
  17553. * for more info check WebGl documentations
  17554. */
  17555. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17556. /**
  17557. * 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:
  17558. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17559. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17560. * 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.
  17561. */
  17562. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17563. /**
  17564. * 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.
  17565. * The default value is -1 which means don't break the query and wait till the result.
  17566. */
  17567. _this.occlusionRetryCount = -1;
  17568. _this._occlusionInternalRetryCounter = 0;
  17569. _this._isOccluded = false;
  17570. _this._isOcclusionQueryInProgress = false;
  17571. _this._visibility = 1.0;
  17572. _this.alphaIndex = Number.MAX_VALUE;
  17573. _this.isVisible = true;
  17574. _this.isPickable = true;
  17575. _this.showBoundingBox = false;
  17576. _this.showSubMeshesBoundingBox = false;
  17577. _this.isBlocker = false;
  17578. _this.enablePointerMoveEvents = false;
  17579. _this.renderingGroupId = 0;
  17580. _this._receiveShadows = false;
  17581. _this.renderOutline = false;
  17582. _this.outlineColor = BABYLON.Color3.Red();
  17583. _this.outlineWidth = 0.02;
  17584. _this.renderOverlay = false;
  17585. _this.overlayColor = BABYLON.Color3.Red();
  17586. _this.overlayAlpha = 0.5;
  17587. _this._hasVertexAlpha = false;
  17588. _this._useVertexColors = true;
  17589. _this._computeBonesUsingShaders = true;
  17590. _this._numBoneInfluencers = 4;
  17591. _this._applyFog = true;
  17592. _this.useOctreeForRenderingSelection = true;
  17593. _this.useOctreeForPicking = true;
  17594. _this.useOctreeForCollisions = true;
  17595. _this._layerMask = 0x0FFFFFFF;
  17596. /**
  17597. * True if the mesh must be rendered in any case.
  17598. */
  17599. _this.alwaysSelectAsActiveMesh = false;
  17600. /**
  17601. * This scene's action manager
  17602. * @type {BABYLON.ActionManager}
  17603. */
  17604. _this.actionManager = null;
  17605. // Physics
  17606. _this.physicsImpostor = null;
  17607. // Collisions
  17608. _this._checkCollisions = false;
  17609. _this._collisionMask = -1;
  17610. _this._collisionGroup = -1;
  17611. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17612. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17613. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17614. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17615. // Edges
  17616. _this.edgesWidth = 1;
  17617. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17618. // Cache
  17619. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17620. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17621. _this._renderId = 0;
  17622. _this._intersectionsInProgress = new Array();
  17623. _this._unIndexed = false;
  17624. _this._lightSources = new Array();
  17625. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17626. if (collidedMesh === void 0) { collidedMesh = null; }
  17627. //TODO move this to the collision coordinator!
  17628. if (_this.getScene().workerCollisions)
  17629. newPosition.multiplyInPlace(_this._collider._radius);
  17630. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17631. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17632. _this.position.addInPlace(_this._diffPositionForCollisions);
  17633. }
  17634. if (collidedMesh) {
  17635. _this.onCollideObservable.notifyObservers(collidedMesh);
  17636. }
  17637. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17638. };
  17639. _this.getScene().addMesh(_this);
  17640. _this._resyncLightSources();
  17641. return _this;
  17642. }
  17643. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17644. get: function () {
  17645. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17646. },
  17647. enumerable: true,
  17648. configurable: true
  17649. });
  17650. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17651. get: function () {
  17652. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17653. },
  17654. enumerable: true,
  17655. configurable: true
  17656. });
  17657. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17658. get: function () {
  17659. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17660. },
  17661. enumerable: true,
  17662. configurable: true
  17663. });
  17664. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17665. get: function () {
  17666. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17667. },
  17668. enumerable: true,
  17669. configurable: true
  17670. });
  17671. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17672. get: function () {
  17673. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17674. },
  17675. enumerable: true,
  17676. configurable: true
  17677. });
  17678. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17679. /**
  17680. * Read-only : the number of facets in the mesh
  17681. */
  17682. get: function () {
  17683. return this._facetNb;
  17684. },
  17685. enumerable: true,
  17686. configurable: true
  17687. });
  17688. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17689. /**
  17690. * The number (integer) of subdivisions per axis in the partioning space
  17691. */
  17692. get: function () {
  17693. return this._partitioningSubdivisions;
  17694. },
  17695. set: function (nb) {
  17696. this._partitioningSubdivisions = nb;
  17697. },
  17698. enumerable: true,
  17699. configurable: true
  17700. });
  17701. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17702. /**
  17703. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17704. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17705. */
  17706. get: function () {
  17707. return this._partitioningBBoxRatio;
  17708. },
  17709. set: function (ratio) {
  17710. this._partitioningBBoxRatio = ratio;
  17711. },
  17712. enumerable: true,
  17713. configurable: true
  17714. });
  17715. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17716. /**
  17717. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17718. * Works only for updatable meshes.
  17719. * Doesn't work with multi-materials.
  17720. */
  17721. get: function () {
  17722. return this._facetDepthSort;
  17723. },
  17724. set: function (sort) {
  17725. this._facetDepthSort = sort;
  17726. },
  17727. enumerable: true,
  17728. configurable: true
  17729. });
  17730. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17731. /**
  17732. * The location (Vector3) where the facet depth sort must be computed from.
  17733. * By default, the active camera position.
  17734. * Used only when facet depth sort is enabled.
  17735. */
  17736. get: function () {
  17737. return this._facetDepthSortFrom;
  17738. },
  17739. set: function (location) {
  17740. this._facetDepthSortFrom = location;
  17741. },
  17742. enumerable: true,
  17743. configurable: true
  17744. });
  17745. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17746. /**
  17747. * Read-only boolean : is the feature facetData enabled ?
  17748. */
  17749. get: function () {
  17750. return this._facetDataEnabled;
  17751. },
  17752. enumerable: true,
  17753. configurable: true
  17754. });
  17755. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17756. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17757. return false;
  17758. }
  17759. this._markSubMeshesAsMiscDirty();
  17760. return true;
  17761. };
  17762. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17763. set: function (callback) {
  17764. if (this._onCollideObserver) {
  17765. this.onCollideObservable.remove(this._onCollideObserver);
  17766. }
  17767. this._onCollideObserver = this.onCollideObservable.add(callback);
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17773. set: function (callback) {
  17774. if (this._onCollisionPositionChangeObserver) {
  17775. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17776. }
  17777. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17783. /**
  17784. * 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.
  17785. */
  17786. get: function () {
  17787. return this._isOccluded;
  17788. },
  17789. set: function (value) {
  17790. this._isOccluded = value;
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17796. /**
  17797. * Flag to check the progress status of the query
  17798. */
  17799. get: function () {
  17800. return this._isOcclusionQueryInProgress;
  17801. },
  17802. enumerable: true,
  17803. configurable: true
  17804. });
  17805. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17806. /**
  17807. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17808. */
  17809. get: function () {
  17810. return this._visibility;
  17811. },
  17812. /**
  17813. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17814. */
  17815. set: function (value) {
  17816. if (this._visibility === value) {
  17817. return;
  17818. }
  17819. this._visibility = value;
  17820. this._markSubMeshesAsMiscDirty();
  17821. },
  17822. enumerable: true,
  17823. configurable: true
  17824. });
  17825. Object.defineProperty(AbstractMesh.prototype, "material", {
  17826. get: function () {
  17827. return this._material;
  17828. },
  17829. set: function (value) {
  17830. if (this._material === value) {
  17831. return;
  17832. }
  17833. this._material = value;
  17834. if (this.onMaterialChangedObservable.hasObservers) {
  17835. this.onMaterialChangedObservable.notifyObservers(this);
  17836. }
  17837. if (!this.subMeshes) {
  17838. return;
  17839. }
  17840. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17841. var subMesh = _a[_i];
  17842. subMesh.setEffect(null);
  17843. }
  17844. },
  17845. enumerable: true,
  17846. configurable: true
  17847. });
  17848. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17849. get: function () {
  17850. return this._receiveShadows;
  17851. },
  17852. set: function (value) {
  17853. if (this._receiveShadows === value) {
  17854. return;
  17855. }
  17856. this._receiveShadows = value;
  17857. this._markSubMeshesAsLightDirty();
  17858. },
  17859. enumerable: true,
  17860. configurable: true
  17861. });
  17862. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17863. get: function () {
  17864. return this._hasVertexAlpha;
  17865. },
  17866. set: function (value) {
  17867. if (this._hasVertexAlpha === value) {
  17868. return;
  17869. }
  17870. this._hasVertexAlpha = value;
  17871. this._markSubMeshesAsAttributesDirty();
  17872. this._markSubMeshesAsMiscDirty();
  17873. },
  17874. enumerable: true,
  17875. configurable: true
  17876. });
  17877. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17878. get: function () {
  17879. return this._useVertexColors;
  17880. },
  17881. set: function (value) {
  17882. if (this._useVertexColors === value) {
  17883. return;
  17884. }
  17885. this._useVertexColors = value;
  17886. this._markSubMeshesAsAttributesDirty();
  17887. },
  17888. enumerable: true,
  17889. configurable: true
  17890. });
  17891. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17892. get: function () {
  17893. return this._computeBonesUsingShaders;
  17894. },
  17895. set: function (value) {
  17896. if (this._computeBonesUsingShaders === value) {
  17897. return;
  17898. }
  17899. this._computeBonesUsingShaders = value;
  17900. this._markSubMeshesAsAttributesDirty();
  17901. },
  17902. enumerable: true,
  17903. configurable: true
  17904. });
  17905. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17906. get: function () {
  17907. return this._numBoneInfluencers;
  17908. },
  17909. set: function (value) {
  17910. if (this._numBoneInfluencers === value) {
  17911. return;
  17912. }
  17913. this._numBoneInfluencers = value;
  17914. this._markSubMeshesAsAttributesDirty();
  17915. },
  17916. enumerable: true,
  17917. configurable: true
  17918. });
  17919. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17920. get: function () {
  17921. return this._applyFog;
  17922. },
  17923. set: function (value) {
  17924. if (this._applyFog === value) {
  17925. return;
  17926. }
  17927. this._applyFog = value;
  17928. this._markSubMeshesAsMiscDirty();
  17929. },
  17930. enumerable: true,
  17931. configurable: true
  17932. });
  17933. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17934. get: function () {
  17935. return this._layerMask;
  17936. },
  17937. set: function (value) {
  17938. if (value === this._layerMask) {
  17939. return;
  17940. }
  17941. this._layerMask = value;
  17942. this._resyncLightSources();
  17943. },
  17944. enumerable: true,
  17945. configurable: true
  17946. });
  17947. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17948. get: function () {
  17949. return this._collisionMask;
  17950. },
  17951. set: function (mask) {
  17952. this._collisionMask = !isNaN(mask) ? mask : -1;
  17953. },
  17954. enumerable: true,
  17955. configurable: true
  17956. });
  17957. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17958. get: function () {
  17959. return this._collisionGroup;
  17960. },
  17961. set: function (mask) {
  17962. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17963. },
  17964. enumerable: true,
  17965. configurable: true
  17966. });
  17967. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17968. get: function () {
  17969. return null;
  17970. },
  17971. enumerable: true,
  17972. configurable: true
  17973. });
  17974. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17975. get: function () {
  17976. return this._skeleton;
  17977. },
  17978. set: function (value) {
  17979. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17980. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17981. }
  17982. if (value && value.needInitialSkinMatrix) {
  17983. value._registerMeshWithPoseMatrix(this);
  17984. }
  17985. this._skeleton = value;
  17986. if (!this._skeleton) {
  17987. this._bonesTransformMatrices = null;
  17988. }
  17989. this._markSubMeshesAsAttributesDirty();
  17990. },
  17991. enumerable: true,
  17992. configurable: true
  17993. });
  17994. /**
  17995. * Returns the string "AbstractMesh"
  17996. */
  17997. AbstractMesh.prototype.getClassName = function () {
  17998. return "AbstractMesh";
  17999. };
  18000. /**
  18001. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18002. */
  18003. AbstractMesh.prototype.toString = function (fullDetails) {
  18004. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  18005. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  18006. if (this._skeleton) {
  18007. ret += ", skeleton: " + this._skeleton.name;
  18008. }
  18009. if (fullDetails) {
  18010. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  18011. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  18012. }
  18013. return ret;
  18014. };
  18015. AbstractMesh.prototype._rebuild = function () {
  18016. if (this._occlusionQuery) {
  18017. this._occlusionQuery = null;
  18018. }
  18019. if (this._edgesRenderer) {
  18020. this._edgesRenderer._rebuild();
  18021. }
  18022. if (!this.subMeshes) {
  18023. return;
  18024. }
  18025. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18026. var subMesh = _a[_i];
  18027. subMesh._rebuild();
  18028. }
  18029. };
  18030. AbstractMesh.prototype._resyncLightSources = function () {
  18031. this._lightSources.length = 0;
  18032. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  18033. var light = _a[_i];
  18034. if (!light.isEnabled()) {
  18035. continue;
  18036. }
  18037. if (light.canAffectMesh(this)) {
  18038. this._lightSources.push(light);
  18039. }
  18040. }
  18041. this._markSubMeshesAsLightDirty();
  18042. };
  18043. AbstractMesh.prototype._resyncLighSource = function (light) {
  18044. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18045. var index = this._lightSources.indexOf(light);
  18046. if (index === -1) {
  18047. if (!isIn) {
  18048. return;
  18049. }
  18050. this._lightSources.push(light);
  18051. }
  18052. else {
  18053. if (isIn) {
  18054. return;
  18055. }
  18056. this._lightSources.splice(index, 1);
  18057. }
  18058. this._markSubMeshesAsLightDirty();
  18059. };
  18060. AbstractMesh.prototype._removeLightSource = function (light) {
  18061. var index = this._lightSources.indexOf(light);
  18062. if (index === -1) {
  18063. return;
  18064. }
  18065. this._lightSources.splice(index, 1);
  18066. this._markSubMeshesAsLightDirty();
  18067. };
  18068. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18069. if (!this.subMeshes) {
  18070. return;
  18071. }
  18072. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18073. var subMesh = _a[_i];
  18074. if (subMesh._materialDefines) {
  18075. func(subMesh._materialDefines);
  18076. }
  18077. }
  18078. };
  18079. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18080. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18081. };
  18082. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18083. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18084. };
  18085. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18086. if (!this.subMeshes) {
  18087. return;
  18088. }
  18089. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18090. var subMesh = _a[_i];
  18091. var material = subMesh.getMaterial();
  18092. if (material) {
  18093. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18094. }
  18095. }
  18096. };
  18097. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18098. /**
  18099. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18100. * Default : (1.0, 1.0, 1.0)
  18101. */
  18102. get: function () {
  18103. return this._scaling;
  18104. },
  18105. /**
  18106. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18107. * Default : (1.0, 1.0, 1.0)
  18108. */
  18109. set: function (newScaling) {
  18110. this._scaling = newScaling;
  18111. if (this.physicsImpostor) {
  18112. this.physicsImpostor.forceUpdate();
  18113. }
  18114. },
  18115. enumerable: true,
  18116. configurable: true
  18117. });
  18118. // Methods
  18119. /**
  18120. * Disables the mesh edger rendering mode.
  18121. * Returns the AbstractMesh.
  18122. */
  18123. AbstractMesh.prototype.disableEdgesRendering = function () {
  18124. if (this._edgesRenderer) {
  18125. this._edgesRenderer.dispose();
  18126. this._edgesRenderer = null;
  18127. }
  18128. return this;
  18129. };
  18130. /**
  18131. * Enables the edge rendering mode on the mesh.
  18132. * This mode makes the mesh edges visible.
  18133. * Returns the AbstractMesh.
  18134. */
  18135. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18136. if (epsilon === void 0) { epsilon = 0.95; }
  18137. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18138. this.disableEdgesRendering();
  18139. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18140. return this;
  18141. };
  18142. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18143. /**
  18144. * Returns true if the mesh is blocked. Used by the class Mesh.
  18145. * Returns the boolean `false` by default.
  18146. */
  18147. get: function () {
  18148. return false;
  18149. },
  18150. enumerable: true,
  18151. configurable: true
  18152. });
  18153. /**
  18154. * Returns the mesh itself by default, used by the class Mesh.
  18155. * Returned type : AbstractMesh
  18156. */
  18157. AbstractMesh.prototype.getLOD = function (camera) {
  18158. return this;
  18159. };
  18160. /**
  18161. * Returns 0 by default, used by the class Mesh.
  18162. * Returns an integer.
  18163. */
  18164. AbstractMesh.prototype.getTotalVertices = function () {
  18165. return 0;
  18166. };
  18167. /**
  18168. * Returns null by default, used by the class Mesh.
  18169. * Returned type : integer array
  18170. */
  18171. AbstractMesh.prototype.getIndices = function () {
  18172. return null;
  18173. };
  18174. /**
  18175. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18176. * Returned type : float array or Float32Array
  18177. */
  18178. AbstractMesh.prototype.getVerticesData = function (kind) {
  18179. return null;
  18180. };
  18181. /**
  18182. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18183. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18184. * The `data` are either a numeric array either a Float32Array.
  18185. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18186. * 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).
  18187. * Note that a new underlying VertexBuffer object is created each call.
  18188. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18189. *
  18190. * Possible `kind` values :
  18191. * - BABYLON.VertexBuffer.PositionKind
  18192. * - BABYLON.VertexBuffer.UVKind
  18193. * - BABYLON.VertexBuffer.UV2Kind
  18194. * - BABYLON.VertexBuffer.UV3Kind
  18195. * - BABYLON.VertexBuffer.UV4Kind
  18196. * - BABYLON.VertexBuffer.UV5Kind
  18197. * - BABYLON.VertexBuffer.UV6Kind
  18198. * - BABYLON.VertexBuffer.ColorKind
  18199. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18200. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18201. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18202. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18203. *
  18204. * Returns the Mesh.
  18205. */
  18206. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18207. return this;
  18208. };
  18209. /**
  18210. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18211. * If the mesh has no geometry, it is simply returned as it is.
  18212. * The `data` are either a numeric array either a Float32Array.
  18213. * No new underlying VertexBuffer object is created.
  18214. * 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.
  18215. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18216. *
  18217. * Possible `kind` values :
  18218. * - BABYLON.VertexBuffer.PositionKind
  18219. * - BABYLON.VertexBuffer.UVKind
  18220. * - BABYLON.VertexBuffer.UV2Kind
  18221. * - BABYLON.VertexBuffer.UV3Kind
  18222. * - BABYLON.VertexBuffer.UV4Kind
  18223. * - BABYLON.VertexBuffer.UV5Kind
  18224. * - BABYLON.VertexBuffer.UV6Kind
  18225. * - BABYLON.VertexBuffer.ColorKind
  18226. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18227. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18228. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18229. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18230. *
  18231. * Returns the Mesh.
  18232. */
  18233. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18234. return this;
  18235. };
  18236. /**
  18237. * Sets the mesh indices.
  18238. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18239. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18240. * This method creates a new index buffer each call.
  18241. * Returns the Mesh.
  18242. */
  18243. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18244. return this;
  18245. };
  18246. /** Returns false by default, used by the class Mesh.
  18247. * Returns a boolean
  18248. */
  18249. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18250. return false;
  18251. };
  18252. /**
  18253. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18254. * Returns a BoundingInfo
  18255. */
  18256. AbstractMesh.prototype.getBoundingInfo = function () {
  18257. if (this._masterMesh) {
  18258. return this._masterMesh.getBoundingInfo();
  18259. }
  18260. if (!this._boundingInfo) {
  18261. // this._boundingInfo is being created here
  18262. this._updateBoundingInfo();
  18263. }
  18264. // cannot be null.
  18265. return this._boundingInfo;
  18266. };
  18267. /**
  18268. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18269. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18270. */
  18271. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18272. if (includeDescendants === void 0) { includeDescendants = true; }
  18273. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18274. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18275. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18276. if (maxDimension === 0) {
  18277. return this;
  18278. }
  18279. var scale = 1 / maxDimension;
  18280. this.scaling.scaleInPlace(scale);
  18281. return this;
  18282. };
  18283. /**
  18284. * Sets a mesh new object BoundingInfo.
  18285. * Returns the AbstractMesh.
  18286. */
  18287. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18288. this._boundingInfo = boundingInfo;
  18289. return this;
  18290. };
  18291. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18292. get: function () {
  18293. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18294. },
  18295. enumerable: true,
  18296. configurable: true
  18297. });
  18298. AbstractMesh.prototype._preActivate = function () {
  18299. };
  18300. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18301. };
  18302. AbstractMesh.prototype._activate = function (renderId) {
  18303. this._renderId = renderId;
  18304. };
  18305. /**
  18306. * Returns the latest update of the World matrix
  18307. * Returns a Matrix.
  18308. */
  18309. AbstractMesh.prototype.getWorldMatrix = function () {
  18310. if (this._masterMesh) {
  18311. return this._masterMesh.getWorldMatrix();
  18312. }
  18313. return _super.prototype.getWorldMatrix.call(this);
  18314. };
  18315. /**
  18316. * Returns the latest update of the World matrix determinant.
  18317. */
  18318. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18319. if (this._masterMesh) {
  18320. return this._masterMesh._getWorldMatrixDeterminant();
  18321. }
  18322. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18323. };
  18324. // ================================== Point of View Movement =================================
  18325. /**
  18326. * Perform relative position change from the point of view of behind the front of the mesh.
  18327. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18328. * Supports definition of mesh facing forward or backward.
  18329. * @param {number} amountRight
  18330. * @param {number} amountUp
  18331. * @param {number} amountForward
  18332. *
  18333. * Returns the AbstractMesh.
  18334. */
  18335. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18336. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18337. return this;
  18338. };
  18339. /**
  18340. * Calculate relative position change from the point of view of behind the front of the mesh.
  18341. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18342. * Supports definition of mesh facing forward or backward.
  18343. * @param {number} amountRight
  18344. * @param {number} amountUp
  18345. * @param {number} amountForward
  18346. *
  18347. * Returns a new Vector3.
  18348. */
  18349. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18350. var rotMatrix = new BABYLON.Matrix();
  18351. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18352. rotQuaternion.toRotationMatrix(rotMatrix);
  18353. var translationDelta = BABYLON.Vector3.Zero();
  18354. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18355. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18356. return translationDelta;
  18357. };
  18358. // ================================== Point of View Rotation =================================
  18359. /**
  18360. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18361. * Supports definition of mesh facing forward or backward.
  18362. * @param {number} flipBack
  18363. * @param {number} twirlClockwise
  18364. * @param {number} tiltRight
  18365. *
  18366. * Returns the AbstractMesh.
  18367. */
  18368. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18369. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18370. return this;
  18371. };
  18372. /**
  18373. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18374. * Supports definition of mesh facing forward or backward.
  18375. * @param {number} flipBack
  18376. * @param {number} twirlClockwise
  18377. * @param {number} tiltRight
  18378. *
  18379. * Returns a new Vector3.
  18380. */
  18381. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18382. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18383. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18384. };
  18385. /**
  18386. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18387. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18388. */
  18389. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18390. if (includeDescendants === void 0) { includeDescendants = true; }
  18391. this.computeWorldMatrix(true);
  18392. var min;
  18393. var max;
  18394. var boundingInfo = this.getBoundingInfo();
  18395. if (!this.subMeshes) {
  18396. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18397. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18398. }
  18399. else {
  18400. min = boundingInfo.boundingBox.minimumWorld;
  18401. max = boundingInfo.boundingBox.maximumWorld;
  18402. }
  18403. if (includeDescendants) {
  18404. var descendants = this.getDescendants(false);
  18405. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18406. var descendant = descendants_1[_i];
  18407. var childMesh = descendant;
  18408. childMesh.computeWorldMatrix(true);
  18409. //make sure we have the needed params to get mix and max
  18410. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18411. continue;
  18412. }
  18413. var childBoundingInfo = childMesh.getBoundingInfo();
  18414. var boundingBox = childBoundingInfo.boundingBox;
  18415. var minBox = boundingBox.minimumWorld;
  18416. var maxBox = boundingBox.maximumWorld;
  18417. BABYLON.Tools.CheckExtends(minBox, min, max);
  18418. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18419. }
  18420. }
  18421. return {
  18422. min: min,
  18423. max: max
  18424. };
  18425. };
  18426. /**
  18427. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18428. * Returns the AbstractMesh.
  18429. */
  18430. AbstractMesh.prototype._updateBoundingInfo = function () {
  18431. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18432. this._boundingInfo.update(this.worldMatrixFromCache);
  18433. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18434. return this;
  18435. };
  18436. /**
  18437. * Update a mesh's children BoundingInfo objects only.
  18438. * Returns the AbstractMesh.
  18439. */
  18440. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18441. if (!this.subMeshes) {
  18442. return this;
  18443. }
  18444. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18445. var subMesh = this.subMeshes[subIndex];
  18446. if (!subMesh.IsGlobal) {
  18447. subMesh.updateBoundingInfo(matrix);
  18448. }
  18449. }
  18450. return this;
  18451. };
  18452. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18453. // Bounding info
  18454. this._updateBoundingInfo();
  18455. };
  18456. /**
  18457. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18458. * A mesh is in the frustum if its bounding box intersects the frustum.
  18459. * Boolean returned.
  18460. */
  18461. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18462. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18463. };
  18464. /**
  18465. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18466. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18467. * Boolean returned.
  18468. */
  18469. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18470. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18471. ;
  18472. };
  18473. /**
  18474. * True if the mesh intersects another mesh or a SolidParticle object.
  18475. * 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)
  18476. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18477. * Returns a boolean.
  18478. */
  18479. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18480. if (precise === void 0) { precise = false; }
  18481. if (!this._boundingInfo || !mesh._boundingInfo) {
  18482. return false;
  18483. }
  18484. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18485. return true;
  18486. }
  18487. if (includeDescendants) {
  18488. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18489. var child = _a[_i];
  18490. if (child.intersectsMesh(mesh, precise, true)) {
  18491. return true;
  18492. }
  18493. }
  18494. }
  18495. return false;
  18496. };
  18497. /**
  18498. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18499. * Returns a boolean.
  18500. */
  18501. AbstractMesh.prototype.intersectsPoint = function (point) {
  18502. if (!this._boundingInfo) {
  18503. return false;
  18504. }
  18505. return this._boundingInfo.intersectsPoint(point);
  18506. };
  18507. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18508. return this.physicsImpostor;
  18509. };
  18510. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18511. if (camera === void 0) { camera = null; }
  18512. if (!camera) {
  18513. camera = this.getScene().activeCamera;
  18514. }
  18515. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18516. };
  18517. /**
  18518. * Returns the distance from the mesh to the active camera.
  18519. * Returns a float.
  18520. */
  18521. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18522. if (camera === void 0) { camera = null; }
  18523. if (!camera) {
  18524. camera = this.getScene().activeCamera;
  18525. }
  18526. return this.absolutePosition.subtract(camera.position).length();
  18527. };
  18528. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18529. if (!this.physicsImpostor) {
  18530. return this;
  18531. }
  18532. this.physicsImpostor.applyImpulse(force, contactPoint);
  18533. return this;
  18534. };
  18535. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18536. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18537. return this;
  18538. }
  18539. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18540. mainPivot: pivot1,
  18541. connectedPivot: pivot2,
  18542. nativeParams: options
  18543. });
  18544. return this;
  18545. };
  18546. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18547. // Collisions
  18548. /**
  18549. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18550. * Default `false`.
  18551. */
  18552. get: function () {
  18553. return this._checkCollisions;
  18554. },
  18555. set: function (collisionEnabled) {
  18556. this._checkCollisions = collisionEnabled;
  18557. if (this.getScene().workerCollisions) {
  18558. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18559. }
  18560. },
  18561. enumerable: true,
  18562. configurable: true
  18563. });
  18564. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18565. /**
  18566. * Gets Collider object used to compute collisions (not physics)
  18567. */
  18568. get: function () {
  18569. return this._collider;
  18570. },
  18571. enumerable: true,
  18572. configurable: true
  18573. });
  18574. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18575. var globalPosition = this.getAbsolutePosition();
  18576. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18577. if (!this._collider) {
  18578. this._collider = new BABYLON.Collider();
  18579. }
  18580. this._collider._radius = this.ellipsoid;
  18581. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18582. return this;
  18583. };
  18584. // Submeshes octree
  18585. /**
  18586. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18587. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18588. * Returns an Octree of submeshes.
  18589. */
  18590. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18591. if (maxCapacity === void 0) { maxCapacity = 64; }
  18592. if (maxDepth === void 0) { maxDepth = 2; }
  18593. if (!this._submeshesOctree) {
  18594. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18595. }
  18596. this.computeWorldMatrix(true);
  18597. var boundingInfo = this.getBoundingInfo();
  18598. // Update octree
  18599. var bbox = boundingInfo.boundingBox;
  18600. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18601. return this._submeshesOctree;
  18602. };
  18603. // Collisions
  18604. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18605. this._generatePointsArray();
  18606. if (!this._positions) {
  18607. return this;
  18608. }
  18609. // Transformation
  18610. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18611. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18612. subMesh._lastColliderWorldVertices = [];
  18613. subMesh._trianglePlanes = [];
  18614. var start = subMesh.verticesStart;
  18615. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18616. for (var i = start; i < end; i++) {
  18617. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18618. }
  18619. }
  18620. // Collide
  18621. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18622. if (collider.collisionFound) {
  18623. collider.collidedMesh = this;
  18624. }
  18625. return this;
  18626. };
  18627. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18628. var subMeshes;
  18629. var len;
  18630. // Octrees
  18631. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18632. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18633. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18634. len = intersections.length;
  18635. subMeshes = intersections.data;
  18636. }
  18637. else {
  18638. subMeshes = this.subMeshes;
  18639. len = subMeshes.length;
  18640. }
  18641. for (var index = 0; index < len; index++) {
  18642. var subMesh = subMeshes[index];
  18643. // Bounding test
  18644. if (len > 1 && !subMesh._checkCollision(collider))
  18645. continue;
  18646. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18647. }
  18648. return this;
  18649. };
  18650. AbstractMesh.prototype._checkCollision = function (collider) {
  18651. // Bounding box test
  18652. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18653. return this;
  18654. // Transformation matrix
  18655. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18656. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18657. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18658. return this;
  18659. };
  18660. // Picking
  18661. AbstractMesh.prototype._generatePointsArray = function () {
  18662. return false;
  18663. };
  18664. /**
  18665. * Checks if the passed Ray intersects with the mesh.
  18666. * Returns an object PickingInfo.
  18667. */
  18668. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18669. var pickingInfo = new BABYLON.PickingInfo();
  18670. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18671. return pickingInfo;
  18672. }
  18673. if (!this._generatePointsArray()) {
  18674. return pickingInfo;
  18675. }
  18676. var intersectInfo = null;
  18677. // Octrees
  18678. var subMeshes;
  18679. var len;
  18680. if (this._submeshesOctree && this.useOctreeForPicking) {
  18681. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18682. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18683. len = intersections.length;
  18684. subMeshes = intersections.data;
  18685. }
  18686. else {
  18687. subMeshes = this.subMeshes;
  18688. len = subMeshes.length;
  18689. }
  18690. for (var index = 0; index < len; index++) {
  18691. var subMesh = subMeshes[index];
  18692. // Bounding test
  18693. if (len > 1 && !subMesh.canIntersects(ray))
  18694. continue;
  18695. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18696. if (currentIntersectInfo) {
  18697. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18698. intersectInfo = currentIntersectInfo;
  18699. intersectInfo.subMeshId = index;
  18700. if (fastCheck) {
  18701. break;
  18702. }
  18703. }
  18704. }
  18705. }
  18706. if (intersectInfo) {
  18707. // Get picked point
  18708. var world = this.getWorldMatrix();
  18709. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18710. var direction = ray.direction.clone();
  18711. direction = direction.scale(intersectInfo.distance);
  18712. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18713. var pickedPoint = worldOrigin.add(worldDirection);
  18714. // Return result
  18715. pickingInfo.hit = true;
  18716. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18717. pickingInfo.pickedPoint = pickedPoint;
  18718. pickingInfo.pickedMesh = this;
  18719. pickingInfo.bu = intersectInfo.bu || 0;
  18720. pickingInfo.bv = intersectInfo.bv || 0;
  18721. pickingInfo.faceId = intersectInfo.faceId;
  18722. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18723. return pickingInfo;
  18724. }
  18725. return pickingInfo;
  18726. };
  18727. /**
  18728. * Clones the mesh, used by the class Mesh.
  18729. * Just returns `null` for an AbstractMesh.
  18730. */
  18731. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18732. return null;
  18733. };
  18734. /**
  18735. * Disposes all the mesh submeshes.
  18736. * Returns the AbstractMesh.
  18737. */
  18738. AbstractMesh.prototype.releaseSubMeshes = function () {
  18739. if (this.subMeshes) {
  18740. while (this.subMeshes.length) {
  18741. this.subMeshes[0].dispose();
  18742. }
  18743. }
  18744. else {
  18745. this.subMeshes = new Array();
  18746. }
  18747. return this;
  18748. };
  18749. /**
  18750. * Releases resources associated with this abstract mesh.
  18751. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18752. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18753. */
  18754. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18755. var _this = this;
  18756. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18757. var index;
  18758. // Smart Array Retainers.
  18759. this.getScene().freeActiveMeshes();
  18760. this.getScene().freeRenderingGroups();
  18761. // Action manager
  18762. if (this.actionManager !== undefined && this.actionManager !== null) {
  18763. this.actionManager.dispose();
  18764. this.actionManager = null;
  18765. }
  18766. // Skeleton
  18767. this._skeleton = null;
  18768. // Physics
  18769. if (this.physicsImpostor) {
  18770. this.physicsImpostor.dispose();
  18771. }
  18772. // Intersections in progress
  18773. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18774. var other = this._intersectionsInProgress[index];
  18775. var pos = other._intersectionsInProgress.indexOf(this);
  18776. other._intersectionsInProgress.splice(pos, 1);
  18777. }
  18778. this._intersectionsInProgress = [];
  18779. // Lights
  18780. var lights = this.getScene().lights;
  18781. lights.forEach(function (light) {
  18782. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18783. if (meshIndex !== -1) {
  18784. light.includedOnlyMeshes.splice(meshIndex, 1);
  18785. }
  18786. meshIndex = light.excludedMeshes.indexOf(_this);
  18787. if (meshIndex !== -1) {
  18788. light.excludedMeshes.splice(meshIndex, 1);
  18789. }
  18790. // Shadow generators
  18791. var generator = light.getShadowGenerator();
  18792. if (generator) {
  18793. var shadowMap = generator.getShadowMap();
  18794. if (shadowMap && shadowMap.renderList) {
  18795. meshIndex = shadowMap.renderList.indexOf(_this);
  18796. if (meshIndex !== -1) {
  18797. shadowMap.renderList.splice(meshIndex, 1);
  18798. }
  18799. }
  18800. }
  18801. });
  18802. // Edges
  18803. if (this._edgesRenderer) {
  18804. this._edgesRenderer.dispose();
  18805. this._edgesRenderer = null;
  18806. }
  18807. // SubMeshes
  18808. if (this.getClassName() !== "InstancedMesh") {
  18809. this.releaseSubMeshes();
  18810. }
  18811. // Octree
  18812. var sceneOctree = this.getScene().selectionOctree;
  18813. if (sceneOctree !== undefined && sceneOctree !== null) {
  18814. var index = sceneOctree.dynamicContent.indexOf(this);
  18815. if (index !== -1) {
  18816. sceneOctree.dynamicContent.splice(index, 1);
  18817. }
  18818. }
  18819. // Query
  18820. var engine = this.getScene().getEngine();
  18821. if (this._occlusionQuery) {
  18822. this._isOcclusionQueryInProgress = false;
  18823. engine.deleteQuery(this._occlusionQuery);
  18824. this._occlusionQuery = null;
  18825. }
  18826. // Engine
  18827. engine.wipeCaches();
  18828. // Remove from scene
  18829. this.getScene().removeMesh(this);
  18830. if (disposeMaterialAndTextures) {
  18831. if (this.material) {
  18832. this.material.dispose(false, true);
  18833. }
  18834. }
  18835. if (!doNotRecurse) {
  18836. // Particles
  18837. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18838. if (this.getScene().particleSystems[index].emitter === this) {
  18839. this.getScene().particleSystems[index].dispose();
  18840. index--;
  18841. }
  18842. }
  18843. }
  18844. // facet data
  18845. if (this._facetDataEnabled) {
  18846. this.disableFacetData();
  18847. }
  18848. this.onAfterWorldMatrixUpdateObservable.clear();
  18849. this.onCollideObservable.clear();
  18850. this.onCollisionPositionChangeObservable.clear();
  18851. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18852. };
  18853. /**
  18854. * Adds the passed mesh as a child to the current mesh.
  18855. * Returns the AbstractMesh.
  18856. */
  18857. AbstractMesh.prototype.addChild = function (mesh) {
  18858. mesh.setParent(this);
  18859. return this;
  18860. };
  18861. /**
  18862. * Removes the passed mesh from the current mesh children list.
  18863. * Returns the AbstractMesh.
  18864. */
  18865. AbstractMesh.prototype.removeChild = function (mesh) {
  18866. mesh.setParent(null);
  18867. return this;
  18868. };
  18869. // Facet data
  18870. /**
  18871. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18872. * Returns the AbstractMesh.
  18873. */
  18874. AbstractMesh.prototype._initFacetData = function () {
  18875. if (!this._facetNormals) {
  18876. this._facetNormals = new Array();
  18877. }
  18878. if (!this._facetPositions) {
  18879. this._facetPositions = new Array();
  18880. }
  18881. if (!this._facetPartitioning) {
  18882. this._facetPartitioning = new Array();
  18883. }
  18884. this._facetNb = (this.getIndices().length / 3) | 0;
  18885. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18886. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18887. for (var f = 0; f < this._facetNb; f++) {
  18888. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18889. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18890. }
  18891. this._facetDataEnabled = true;
  18892. return this;
  18893. };
  18894. /**
  18895. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18896. * This method can be called within the render loop.
  18897. * 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.
  18898. * Returns the AbstractMesh.
  18899. */
  18900. AbstractMesh.prototype.updateFacetData = function () {
  18901. if (!this._facetDataEnabled) {
  18902. this._initFacetData();
  18903. }
  18904. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18905. var indices = this.getIndices();
  18906. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18907. var bInfo = this.getBoundingInfo();
  18908. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18909. // init arrays, matrix and sort function on first call
  18910. this._facetDepthSortEnabled = true;
  18911. if (indices instanceof Uint16Array) {
  18912. this._depthSortedIndices = new Uint16Array(indices);
  18913. }
  18914. else if (indices instanceof Uint32Array) {
  18915. this._depthSortedIndices = new Uint32Array(indices);
  18916. }
  18917. else {
  18918. var needs32bits = false;
  18919. for (var i = 0; i < indices.length; i++) {
  18920. if (indices[i] > 65535) {
  18921. needs32bits = true;
  18922. break;
  18923. }
  18924. }
  18925. if (needs32bits) {
  18926. this._depthSortedIndices = new Uint32Array(indices);
  18927. }
  18928. else {
  18929. this._depthSortedIndices = new Uint16Array(indices);
  18930. }
  18931. }
  18932. this._facetDepthSortFunction = function (f1, f2) {
  18933. return (f2.sqDistance - f1.sqDistance);
  18934. };
  18935. if (!this._facetDepthSortFrom) {
  18936. var camera = this.getScene().activeCamera;
  18937. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18938. }
  18939. this._depthSortedFacets = [];
  18940. for (var f = 0; f < this._facetNb; f++) {
  18941. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18942. this._depthSortedFacets.push(depthSortedFacet);
  18943. }
  18944. this._invertedMatrix = BABYLON.Matrix.Identity();
  18945. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18946. }
  18947. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18948. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18949. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18950. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18951. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18952. this._subDiv.max = this._partitioningSubdivisions;
  18953. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18954. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18955. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18956. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18957. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18958. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18959. // set the parameters for ComputeNormals()
  18960. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18961. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18962. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18963. this._facetParameters.bInfo = bInfo;
  18964. this._facetParameters.bbSize = this._bbSize;
  18965. this._facetParameters.subDiv = this._subDiv;
  18966. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18967. this._facetParameters.depthSort = this._facetDepthSort;
  18968. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18969. this.computeWorldMatrix(true);
  18970. this._worldMatrix.invertToRef(this._invertedMatrix);
  18971. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18972. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18973. }
  18974. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18975. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18976. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18977. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18978. var l = (this._depthSortedIndices.length / 3) | 0;
  18979. for (var f = 0; f < l; f++) {
  18980. var sind = this._depthSortedFacets[f].ind;
  18981. this._depthSortedIndices[f * 3] = indices[sind];
  18982. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18983. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18984. }
  18985. this.updateIndices(this._depthSortedIndices);
  18986. }
  18987. return this;
  18988. };
  18989. /**
  18990. * Returns the facetLocalNormals array.
  18991. * The normals are expressed in the mesh local space.
  18992. */
  18993. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18994. if (!this._facetNormals) {
  18995. this.updateFacetData();
  18996. }
  18997. return this._facetNormals;
  18998. };
  18999. /**
  19000. * Returns the facetLocalPositions array.
  19001. * The facet positions are expressed in the mesh local space.
  19002. */
  19003. AbstractMesh.prototype.getFacetLocalPositions = function () {
  19004. if (!this._facetPositions) {
  19005. this.updateFacetData();
  19006. }
  19007. return this._facetPositions;
  19008. };
  19009. /**
  19010. * Returns the facetLocalPartioning array.
  19011. */
  19012. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  19013. if (!this._facetPartitioning) {
  19014. this.updateFacetData();
  19015. }
  19016. return this._facetPartitioning;
  19017. };
  19018. /**
  19019. * Returns the i-th facet position in the world system.
  19020. * This method allocates a new Vector3 per call.
  19021. */
  19022. AbstractMesh.prototype.getFacetPosition = function (i) {
  19023. var pos = BABYLON.Vector3.Zero();
  19024. this.getFacetPositionToRef(i, pos);
  19025. return pos;
  19026. };
  19027. /**
  19028. * Sets the reference Vector3 with the i-th facet position in the world system.
  19029. * Returns the AbstractMesh.
  19030. */
  19031. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  19032. var localPos = (this.getFacetLocalPositions())[i];
  19033. var world = this.getWorldMatrix();
  19034. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  19035. return this;
  19036. };
  19037. /**
  19038. * Returns the i-th facet normal in the world system.
  19039. * This method allocates a new Vector3 per call.
  19040. */
  19041. AbstractMesh.prototype.getFacetNormal = function (i) {
  19042. var norm = BABYLON.Vector3.Zero();
  19043. this.getFacetNormalToRef(i, norm);
  19044. return norm;
  19045. };
  19046. /**
  19047. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19048. * Returns the AbstractMesh.
  19049. */
  19050. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19051. var localNorm = (this.getFacetLocalNormals())[i];
  19052. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19053. return this;
  19054. };
  19055. /**
  19056. * 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).
  19057. */
  19058. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19059. var bInfo = this.getBoundingInfo();
  19060. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19061. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19062. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19063. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19064. return null;
  19065. }
  19066. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19067. };
  19068. /**
  19069. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19070. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19071. * 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.
  19072. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19073. * 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.
  19074. */
  19075. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19076. if (checkFace === void 0) { checkFace = false; }
  19077. if (facing === void 0) { facing = true; }
  19078. var world = this.getWorldMatrix();
  19079. var invMat = BABYLON.Tmp.Matrix[5];
  19080. world.invertToRef(invMat);
  19081. var invVect = BABYLON.Tmp.Vector3[8];
  19082. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19083. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19084. if (projected) {
  19085. // tranform the local computed projected vector to world coordinates
  19086. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19087. }
  19088. return closest;
  19089. };
  19090. /**
  19091. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19092. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19093. * 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.
  19094. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19095. * 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.
  19096. */
  19097. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19098. if (checkFace === void 0) { checkFace = false; }
  19099. if (facing === void 0) { facing = true; }
  19100. var closest = null;
  19101. var tmpx = 0.0;
  19102. var tmpy = 0.0;
  19103. var tmpz = 0.0;
  19104. var d = 0.0; // tmp dot facet normal * facet position
  19105. var t0 = 0.0;
  19106. var projx = 0.0;
  19107. var projy = 0.0;
  19108. var projz = 0.0;
  19109. // Get all the facets in the same partitioning block than (x, y, z)
  19110. var facetPositions = this.getFacetLocalPositions();
  19111. var facetNormals = this.getFacetLocalNormals();
  19112. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19113. if (!facetsInBlock) {
  19114. return null;
  19115. }
  19116. // Get the closest facet to (x, y, z)
  19117. var shortest = Number.MAX_VALUE; // init distance vars
  19118. var tmpDistance = shortest;
  19119. var fib; // current facet in the block
  19120. var norm; // current facet normal
  19121. var p0; // current facet barycenter position
  19122. // loop on all the facets in the current partitioning block
  19123. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19124. fib = facetsInBlock[idx];
  19125. norm = facetNormals[fib];
  19126. p0 = facetPositions[fib];
  19127. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19128. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19129. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19130. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19131. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19132. projx = x + norm.x * t0;
  19133. projy = y + norm.y * t0;
  19134. projz = z + norm.z * t0;
  19135. tmpx = projx - x;
  19136. tmpy = projy - y;
  19137. tmpz = projz - z;
  19138. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19139. if (tmpDistance < shortest) {
  19140. shortest = tmpDistance;
  19141. closest = fib;
  19142. if (projected) {
  19143. projected.x = projx;
  19144. projected.y = projy;
  19145. projected.z = projz;
  19146. }
  19147. }
  19148. }
  19149. }
  19150. return closest;
  19151. };
  19152. /**
  19153. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19154. */
  19155. AbstractMesh.prototype.getFacetDataParameters = function () {
  19156. return this._facetParameters;
  19157. };
  19158. /**
  19159. * Disables the feature FacetData and frees the related memory.
  19160. * Returns the AbstractMesh.
  19161. */
  19162. AbstractMesh.prototype.disableFacetData = function () {
  19163. if (this._facetDataEnabled) {
  19164. this._facetDataEnabled = false;
  19165. this._facetPositions = new Array();
  19166. this._facetNormals = new Array();
  19167. this._facetPartitioning = new Array();
  19168. this._facetParameters = null;
  19169. this._depthSortedIndices = new Uint32Array(0);
  19170. }
  19171. return this;
  19172. };
  19173. /**
  19174. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19175. * Returns the mesh.
  19176. */
  19177. AbstractMesh.prototype.updateIndices = function (indices) {
  19178. return this;
  19179. };
  19180. /**
  19181. * The mesh Geometry. Actually used by the Mesh object.
  19182. * Returns a blank geometry object.
  19183. */
  19184. /**
  19185. * Creates new normals data for the mesh.
  19186. * @param updatable.
  19187. */
  19188. AbstractMesh.prototype.createNormals = function (updatable) {
  19189. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19190. var indices = this.getIndices();
  19191. var normals;
  19192. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19193. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19194. }
  19195. else {
  19196. normals = [];
  19197. }
  19198. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19199. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19200. };
  19201. /**
  19202. * Align the mesh with a normal.
  19203. * Returns the mesh.
  19204. */
  19205. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19206. if (!upDirection) {
  19207. upDirection = BABYLON.Axis.Y;
  19208. }
  19209. var axisX = BABYLON.Tmp.Vector3[0];
  19210. var axisZ = BABYLON.Tmp.Vector3[1];
  19211. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19212. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19213. if (this.rotationQuaternion) {
  19214. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19215. }
  19216. else {
  19217. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19218. }
  19219. return this;
  19220. };
  19221. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19222. var engine = this.getEngine();
  19223. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19224. this._isOccluded = false;
  19225. return;
  19226. }
  19227. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19228. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19229. if (isOcclusionQueryAvailable) {
  19230. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19231. this._isOcclusionQueryInProgress = false;
  19232. this._occlusionInternalRetryCounter = 0;
  19233. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19234. }
  19235. else {
  19236. this._occlusionInternalRetryCounter++;
  19237. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19238. this._isOcclusionQueryInProgress = false;
  19239. this._occlusionInternalRetryCounter = 0;
  19240. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19241. // if strict continue the last state of the object.
  19242. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19243. }
  19244. else {
  19245. return;
  19246. }
  19247. }
  19248. }
  19249. var scene = this.getScene();
  19250. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19251. if (!this._occlusionQuery) {
  19252. this._occlusionQuery = engine.createQuery();
  19253. }
  19254. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19255. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19256. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19257. this._isOcclusionQueryInProgress = true;
  19258. };
  19259. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19260. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19261. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19262. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19263. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19264. return AbstractMesh;
  19265. }(BABYLON.TransformNode));
  19266. BABYLON.AbstractMesh = AbstractMesh;
  19267. })(BABYLON || (BABYLON = {}));
  19268. //# sourceMappingURL=babylon.abstractMesh.js.map
  19269. "use strict";
  19270. var BABYLON;
  19271. (function (BABYLON) {
  19272. /**
  19273. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19274. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19275. * 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.
  19276. */
  19277. var Light = /** @class */ (function (_super) {
  19278. __extends(Light, _super);
  19279. /**
  19280. * Creates a Light object in the scene.
  19281. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19282. * @param name The firendly name of the light
  19283. * @param scene The scene the light belongs too
  19284. */
  19285. function Light(name, scene) {
  19286. var _this = _super.call(this, name, scene) || this;
  19287. /**
  19288. * Diffuse gives the basic color to an object.
  19289. */
  19290. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19291. /**
  19292. * Specular produces a highlight color on an object.
  19293. * Note: This is note affecting PBR materials.
  19294. */
  19295. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19296. /**
  19297. * Strength of the light.
  19298. * Note: By default it is define in the framework own unit.
  19299. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19300. */
  19301. _this.intensity = 1.0;
  19302. /**
  19303. * Defines how far from the source the light is impacting in scene units.
  19304. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19305. */
  19306. _this.range = Number.MAX_VALUE;
  19307. /**
  19308. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19309. * of light.
  19310. */
  19311. _this._photometricScale = 1.0;
  19312. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19313. _this._radius = 0.00001;
  19314. /**
  19315. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19316. * exceeding the number allowed of the materials.
  19317. */
  19318. _this.renderPriority = 0;
  19319. /**
  19320. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19321. * the current shadow generator.
  19322. */
  19323. _this.shadowEnabled = true;
  19324. _this._excludeWithLayerMask = 0;
  19325. _this._includeOnlyWithLayerMask = 0;
  19326. _this._lightmapMode = 0;
  19327. /**
  19328. * @ignore Internal use only.
  19329. */
  19330. _this._excludedMeshesIds = new Array();
  19331. /**
  19332. * @ignore Internal use only.
  19333. */
  19334. _this._includedOnlyMeshesIds = new Array();
  19335. _this.getScene().addLight(_this);
  19336. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19337. _this._buildUniformLayout();
  19338. _this.includedOnlyMeshes = new Array();
  19339. _this.excludedMeshes = new Array();
  19340. _this._resyncMeshes();
  19341. return _this;
  19342. }
  19343. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19344. /**
  19345. * If every light affecting the material is in this lightmapMode,
  19346. * material.lightmapTexture adds or multiplies
  19347. * (depends on material.useLightmapAsShadowmap)
  19348. * after every other light calculations.
  19349. */
  19350. get: function () {
  19351. return Light._LIGHTMAP_DEFAULT;
  19352. },
  19353. enumerable: true,
  19354. configurable: true
  19355. });
  19356. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19357. /**
  19358. * material.lightmapTexture as only diffuse lighting from this light
  19359. * adds only specular lighting from this light
  19360. * adds dynamic shadows
  19361. */
  19362. get: function () {
  19363. return Light._LIGHTMAP_SPECULAR;
  19364. },
  19365. enumerable: true,
  19366. configurable: true
  19367. });
  19368. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19369. /**
  19370. * material.lightmapTexture as only lighting
  19371. * no light calculation from this light
  19372. * only adds dynamic shadows from this light
  19373. */
  19374. get: function () {
  19375. return Light._LIGHTMAP_SHADOWSONLY;
  19376. },
  19377. enumerable: true,
  19378. configurable: true
  19379. });
  19380. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19381. /**
  19382. * Each light type uses the default quantity according to its type:
  19383. * point/spot lights use luminous intensity
  19384. * directional lights use illuminance
  19385. */
  19386. get: function () {
  19387. return Light._INTENSITYMODE_AUTOMATIC;
  19388. },
  19389. enumerable: true,
  19390. configurable: true
  19391. });
  19392. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19393. /**
  19394. * lumen (lm)
  19395. */
  19396. get: function () {
  19397. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19398. },
  19399. enumerable: true,
  19400. configurable: true
  19401. });
  19402. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19403. /**
  19404. * candela (lm/sr)
  19405. */
  19406. get: function () {
  19407. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19413. /**
  19414. * lux (lm/m^2)
  19415. */
  19416. get: function () {
  19417. return Light._INTENSITYMODE_ILLUMINANCE;
  19418. },
  19419. enumerable: true,
  19420. configurable: true
  19421. });
  19422. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19423. /**
  19424. * nit (cd/m^2)
  19425. */
  19426. get: function () {
  19427. return Light._INTENSITYMODE_LUMINANCE;
  19428. },
  19429. enumerable: true,
  19430. configurable: true
  19431. });
  19432. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19433. /**
  19434. * Light type const id of the point light.
  19435. */
  19436. get: function () {
  19437. return Light._LIGHTTYPEID_POINTLIGHT;
  19438. },
  19439. enumerable: true,
  19440. configurable: true
  19441. });
  19442. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19443. /**
  19444. * Light type const id of the directional light.
  19445. */
  19446. get: function () {
  19447. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19448. },
  19449. enumerable: true,
  19450. configurable: true
  19451. });
  19452. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19453. /**
  19454. * Light type const id of the spot light.
  19455. */
  19456. get: function () {
  19457. return Light._LIGHTTYPEID_SPOTLIGHT;
  19458. },
  19459. enumerable: true,
  19460. configurable: true
  19461. });
  19462. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19463. /**
  19464. * Light type const id of the hemispheric light.
  19465. */
  19466. get: function () {
  19467. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19468. },
  19469. enumerable: true,
  19470. configurable: true
  19471. });
  19472. Object.defineProperty(Light.prototype, "intensityMode", {
  19473. /**
  19474. * Gets the photometric scale used to interpret the intensity.
  19475. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19476. */
  19477. get: function () {
  19478. return this._intensityMode;
  19479. },
  19480. /**
  19481. * Sets the photometric scale used to interpret the intensity.
  19482. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19483. */
  19484. set: function (value) {
  19485. this._intensityMode = value;
  19486. this._computePhotometricScale();
  19487. },
  19488. enumerable: true,
  19489. configurable: true
  19490. });
  19491. ;
  19492. ;
  19493. Object.defineProperty(Light.prototype, "radius", {
  19494. /**
  19495. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19496. */
  19497. get: function () {
  19498. return this._radius;
  19499. },
  19500. /**
  19501. * sets the light radius used by PBR Materials to simulate soft area lights.
  19502. */
  19503. set: function (value) {
  19504. this._radius = value;
  19505. this._computePhotometricScale();
  19506. },
  19507. enumerable: true,
  19508. configurable: true
  19509. });
  19510. ;
  19511. ;
  19512. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19513. /**
  19514. * Gets the only meshes impacted by this light.
  19515. */
  19516. get: function () {
  19517. return this._includedOnlyMeshes;
  19518. },
  19519. /**
  19520. * Sets the only meshes impacted by this light.
  19521. */
  19522. set: function (value) {
  19523. this._includedOnlyMeshes = value;
  19524. this._hookArrayForIncludedOnly(value);
  19525. },
  19526. enumerable: true,
  19527. configurable: true
  19528. });
  19529. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19530. /**
  19531. * Gets the meshes not impacted by this light.
  19532. */
  19533. get: function () {
  19534. return this._excludedMeshes;
  19535. },
  19536. /**
  19537. * Sets the meshes not impacted by this light.
  19538. */
  19539. set: function (value) {
  19540. this._excludedMeshes = value;
  19541. this._hookArrayForExcluded(value);
  19542. },
  19543. enumerable: true,
  19544. configurable: true
  19545. });
  19546. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19547. /**
  19548. * Gets the layer id use to find what meshes are not impacted by the light.
  19549. * Inactive if 0
  19550. */
  19551. get: function () {
  19552. return this._excludeWithLayerMask;
  19553. },
  19554. /**
  19555. * Sets the layer id use to find what meshes are not impacted by the light.
  19556. * Inactive if 0
  19557. */
  19558. set: function (value) {
  19559. this._excludeWithLayerMask = value;
  19560. this._resyncMeshes();
  19561. },
  19562. enumerable: true,
  19563. configurable: true
  19564. });
  19565. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19566. /**
  19567. * Gets the layer id use to find what meshes are impacted by the light.
  19568. * Inactive if 0
  19569. */
  19570. get: function () {
  19571. return this._includeOnlyWithLayerMask;
  19572. },
  19573. /**
  19574. * Sets the layer id use to find what meshes are impacted by the light.
  19575. * Inactive if 0
  19576. */
  19577. set: function (value) {
  19578. this._includeOnlyWithLayerMask = value;
  19579. this._resyncMeshes();
  19580. },
  19581. enumerable: true,
  19582. configurable: true
  19583. });
  19584. Object.defineProperty(Light.prototype, "lightmapMode", {
  19585. /**
  19586. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19587. */
  19588. get: function () {
  19589. return this._lightmapMode;
  19590. },
  19591. /**
  19592. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19593. */
  19594. set: function (value) {
  19595. if (this._lightmapMode === value) {
  19596. return;
  19597. }
  19598. this._lightmapMode = value;
  19599. this._markMeshesAsLightDirty();
  19600. },
  19601. enumerable: true,
  19602. configurable: true
  19603. });
  19604. /**
  19605. * Returns the string "Light".
  19606. * @returns the class name
  19607. */
  19608. Light.prototype.getClassName = function () {
  19609. return "Light";
  19610. };
  19611. /**
  19612. * Converts the light information to a readable string for debug purpose.
  19613. * @param fullDetails Supports for multiple levels of logging within scene loading
  19614. * @returns the human readable light info
  19615. */
  19616. Light.prototype.toString = function (fullDetails) {
  19617. var ret = "Name: " + this.name;
  19618. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19619. if (this.animations) {
  19620. for (var i = 0; i < this.animations.length; i++) {
  19621. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19622. }
  19623. }
  19624. if (fullDetails) {
  19625. }
  19626. return ret;
  19627. };
  19628. /**
  19629. * Set the enabled state of this node.
  19630. * @param value - the new enabled state
  19631. * @see isEnabled
  19632. */
  19633. Light.prototype.setEnabled = function (value) {
  19634. _super.prototype.setEnabled.call(this, value);
  19635. this._resyncMeshes();
  19636. };
  19637. /**
  19638. * Returns the Light associated shadow generator if any.
  19639. * @return the associated shadow generator.
  19640. */
  19641. Light.prototype.getShadowGenerator = function () {
  19642. return this._shadowGenerator;
  19643. };
  19644. /**
  19645. * Returns a Vector3, the absolute light position in the World.
  19646. * @returns the world space position of the light
  19647. */
  19648. Light.prototype.getAbsolutePosition = function () {
  19649. return BABYLON.Vector3.Zero();
  19650. };
  19651. /**
  19652. * Specifies if the light will affect the passed mesh.
  19653. * @param mesh The mesh to test against the light
  19654. * @return true the mesh is affected otherwise, false.
  19655. */
  19656. Light.prototype.canAffectMesh = function (mesh) {
  19657. if (!mesh) {
  19658. return true;
  19659. }
  19660. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19661. return false;
  19662. }
  19663. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19664. return false;
  19665. }
  19666. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19667. return false;
  19668. }
  19669. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19670. return false;
  19671. }
  19672. return true;
  19673. };
  19674. /**
  19675. * Computes and Returns the light World matrix.
  19676. * @returns the world matrix
  19677. */
  19678. Light.prototype.getWorldMatrix = function () {
  19679. this._currentRenderId = this.getScene().getRenderId();
  19680. var worldMatrix = this._getWorldMatrix();
  19681. if (this.parent && this.parent.getWorldMatrix) {
  19682. if (!this._parentedWorldMatrix) {
  19683. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19684. }
  19685. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19686. this._markSyncedWithParent();
  19687. return this._parentedWorldMatrix;
  19688. }
  19689. return worldMatrix;
  19690. };
  19691. /**
  19692. * Sort function to order lights for rendering.
  19693. * @param a First Light object to compare to second.
  19694. * @param b Second Light object to compare first.
  19695. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19696. */
  19697. Light.CompareLightsPriority = function (a, b) {
  19698. //shadow-casting lights have priority over non-shadow-casting lights
  19699. //the renderPrioirty is a secondary sort criterion
  19700. if (a.shadowEnabled !== b.shadowEnabled) {
  19701. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19702. }
  19703. return b.renderPriority - a.renderPriority;
  19704. };
  19705. /**
  19706. * Releases resources associated with this node.
  19707. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19708. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19709. */
  19710. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19711. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19712. if (this._shadowGenerator) {
  19713. this._shadowGenerator.dispose();
  19714. this._shadowGenerator = null;
  19715. }
  19716. // Animations
  19717. this.getScene().stopAnimation(this);
  19718. // Remove from meshes
  19719. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19720. var mesh = _a[_i];
  19721. mesh._removeLightSource(this);
  19722. }
  19723. this._uniformBuffer.dispose();
  19724. // Remove from scene
  19725. this.getScene().removeLight(this);
  19726. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19727. };
  19728. /**
  19729. * Returns the light type ID (integer).
  19730. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19731. */
  19732. Light.prototype.getTypeID = function () {
  19733. return 0;
  19734. };
  19735. /**
  19736. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19737. * @returns the scaled intensity in intensity mode unit
  19738. */
  19739. Light.prototype.getScaledIntensity = function () {
  19740. return this._photometricScale * this.intensity;
  19741. };
  19742. /**
  19743. * Returns a new Light object, named "name", from the current one.
  19744. * @param name The name of the cloned light
  19745. * @returns the new created light
  19746. */
  19747. Light.prototype.clone = function (name) {
  19748. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19749. if (!constructor) {
  19750. return null;
  19751. }
  19752. return BABYLON.SerializationHelper.Clone(constructor, this);
  19753. };
  19754. /**
  19755. * Serializes the current light into a Serialization object.
  19756. * @returns the serialized object.
  19757. */
  19758. Light.prototype.serialize = function () {
  19759. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19760. // Type
  19761. serializationObject.type = this.getTypeID();
  19762. // Parent
  19763. if (this.parent) {
  19764. serializationObject.parentId = this.parent.id;
  19765. }
  19766. // Inclusion / exclusions
  19767. if (this.excludedMeshes.length > 0) {
  19768. serializationObject.excludedMeshesIds = [];
  19769. this.excludedMeshes.forEach(function (mesh) {
  19770. serializationObject.excludedMeshesIds.push(mesh.id);
  19771. });
  19772. }
  19773. if (this.includedOnlyMeshes.length > 0) {
  19774. serializationObject.includedOnlyMeshesIds = [];
  19775. this.includedOnlyMeshes.forEach(function (mesh) {
  19776. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19777. });
  19778. }
  19779. // Animations
  19780. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19781. serializationObject.ranges = this.serializeAnimationRanges();
  19782. return serializationObject;
  19783. };
  19784. /**
  19785. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19786. * This new light is named "name" and added to the passed scene.
  19787. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19788. * @param name The friendly name of the light
  19789. * @param scene The scene the new light will belong to
  19790. * @returns the constructor function
  19791. */
  19792. Light.GetConstructorFromName = function (type, name, scene) {
  19793. switch (type) {
  19794. case 0:
  19795. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19796. case 1:
  19797. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19798. case 2:
  19799. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19800. case 3:
  19801. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19802. }
  19803. return null;
  19804. };
  19805. /**
  19806. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19807. * @param parsedLight The JSON representation of the light
  19808. * @param scene The scene to create the parsed light in
  19809. * @returns the created light after parsing
  19810. */
  19811. Light.Parse = function (parsedLight, scene) {
  19812. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19813. if (!constructor) {
  19814. return null;
  19815. }
  19816. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19817. // Inclusion / exclusions
  19818. if (parsedLight.excludedMeshesIds) {
  19819. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19820. }
  19821. if (parsedLight.includedOnlyMeshesIds) {
  19822. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19823. }
  19824. // Parent
  19825. if (parsedLight.parentId) {
  19826. light._waitingParentId = parsedLight.parentId;
  19827. }
  19828. // Animations
  19829. if (parsedLight.animations) {
  19830. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19831. var parsedAnimation = parsedLight.animations[animationIndex];
  19832. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19833. }
  19834. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19835. }
  19836. if (parsedLight.autoAnimate) {
  19837. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19838. }
  19839. return light;
  19840. };
  19841. Light.prototype._hookArrayForExcluded = function (array) {
  19842. var _this = this;
  19843. var oldPush = array.push;
  19844. array.push = function () {
  19845. var items = [];
  19846. for (var _i = 0; _i < arguments.length; _i++) {
  19847. items[_i] = arguments[_i];
  19848. }
  19849. var result = oldPush.apply(array, items);
  19850. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19851. var item = items_1[_a];
  19852. item._resyncLighSource(_this);
  19853. }
  19854. return result;
  19855. };
  19856. var oldSplice = array.splice;
  19857. array.splice = function (index, deleteCount) {
  19858. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19859. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19860. var item = deleted_1[_i];
  19861. item._resyncLighSource(_this);
  19862. }
  19863. return deleted;
  19864. };
  19865. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19866. var item = array_1[_i];
  19867. item._resyncLighSource(this);
  19868. }
  19869. };
  19870. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19871. var _this = this;
  19872. var oldPush = array.push;
  19873. array.push = function () {
  19874. var items = [];
  19875. for (var _i = 0; _i < arguments.length; _i++) {
  19876. items[_i] = arguments[_i];
  19877. }
  19878. var result = oldPush.apply(array, items);
  19879. _this._resyncMeshes();
  19880. return result;
  19881. };
  19882. var oldSplice = array.splice;
  19883. array.splice = function (index, deleteCount) {
  19884. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19885. _this._resyncMeshes();
  19886. return deleted;
  19887. };
  19888. this._resyncMeshes();
  19889. };
  19890. Light.prototype._resyncMeshes = function () {
  19891. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19892. var mesh = _a[_i];
  19893. mesh._resyncLighSource(this);
  19894. }
  19895. };
  19896. /**
  19897. * Forces the meshes to update their light related information in their rendering used effects
  19898. * @ignore Internal Use Only
  19899. */
  19900. Light.prototype._markMeshesAsLightDirty = function () {
  19901. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19902. var mesh = _a[_i];
  19903. if (mesh._lightSources.indexOf(this) !== -1) {
  19904. mesh._markSubMeshesAsLightDirty();
  19905. }
  19906. }
  19907. };
  19908. /**
  19909. * Recomputes the cached photometric scale if needed.
  19910. */
  19911. Light.prototype._computePhotometricScale = function () {
  19912. this._photometricScale = this._getPhotometricScale();
  19913. this.getScene().resetCachedMaterial();
  19914. };
  19915. /**
  19916. * Returns the Photometric Scale according to the light type and intensity mode.
  19917. */
  19918. Light.prototype._getPhotometricScale = function () {
  19919. var photometricScale = 0.0;
  19920. var lightTypeID = this.getTypeID();
  19921. //get photometric mode
  19922. var photometricMode = this.intensityMode;
  19923. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19924. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19925. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19926. }
  19927. else {
  19928. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19929. }
  19930. }
  19931. //compute photometric scale
  19932. switch (lightTypeID) {
  19933. case Light.LIGHTTYPEID_POINTLIGHT:
  19934. case Light.LIGHTTYPEID_SPOTLIGHT:
  19935. switch (photometricMode) {
  19936. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19937. photometricScale = 1.0 / (4.0 * Math.PI);
  19938. break;
  19939. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19940. photometricScale = 1.0;
  19941. break;
  19942. case Light.INTENSITYMODE_LUMINANCE:
  19943. photometricScale = this.radius * this.radius;
  19944. break;
  19945. }
  19946. break;
  19947. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19948. switch (photometricMode) {
  19949. case Light.INTENSITYMODE_ILLUMINANCE:
  19950. photometricScale = 1.0;
  19951. break;
  19952. case Light.INTENSITYMODE_LUMINANCE:
  19953. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19954. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19955. var apexAngleRadians = this.radius;
  19956. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19957. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19958. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19959. photometricScale = solidAngle;
  19960. break;
  19961. }
  19962. break;
  19963. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19964. // No fall off in hemisperic light.
  19965. photometricScale = 1.0;
  19966. break;
  19967. }
  19968. return photometricScale;
  19969. };
  19970. /**
  19971. * Reorder the light in the scene according to their defined priority.
  19972. * @ignore Internal Use Only
  19973. */
  19974. Light.prototype._reorderLightsInScene = function () {
  19975. var scene = this.getScene();
  19976. if (this._renderPriority != 0) {
  19977. scene.requireLightSorting = true;
  19978. }
  19979. this.getScene().sortLightsByPriority();
  19980. };
  19981. //lightmapMode Consts
  19982. Light._LIGHTMAP_DEFAULT = 0;
  19983. Light._LIGHTMAP_SPECULAR = 1;
  19984. Light._LIGHTMAP_SHADOWSONLY = 2;
  19985. // Intensity Mode Consts
  19986. Light._INTENSITYMODE_AUTOMATIC = 0;
  19987. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19988. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19989. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19990. Light._INTENSITYMODE_LUMINANCE = 4;
  19991. // Light types ids const.
  19992. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19993. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19994. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19995. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19996. __decorate([
  19997. BABYLON.serializeAsColor3()
  19998. ], Light.prototype, "diffuse", void 0);
  19999. __decorate([
  20000. BABYLON.serializeAsColor3()
  20001. ], Light.prototype, "specular", void 0);
  20002. __decorate([
  20003. BABYLON.serialize()
  20004. ], Light.prototype, "intensity", void 0);
  20005. __decorate([
  20006. BABYLON.serialize()
  20007. ], Light.prototype, "range", void 0);
  20008. __decorate([
  20009. BABYLON.serialize()
  20010. ], Light.prototype, "intensityMode", null);
  20011. __decorate([
  20012. BABYLON.serialize()
  20013. ], Light.prototype, "radius", null);
  20014. __decorate([
  20015. BABYLON.serialize()
  20016. ], Light.prototype, "_renderPriority", void 0);
  20017. __decorate([
  20018. BABYLON.expandToProperty("_reorderLightsInScene")
  20019. ], Light.prototype, "renderPriority", void 0);
  20020. __decorate([
  20021. BABYLON.serialize()
  20022. ], Light.prototype, "shadowEnabled", void 0);
  20023. __decorate([
  20024. BABYLON.serialize("excludeWithLayerMask")
  20025. ], Light.prototype, "_excludeWithLayerMask", void 0);
  20026. __decorate([
  20027. BABYLON.serialize("includeOnlyWithLayerMask")
  20028. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  20029. __decorate([
  20030. BABYLON.serialize("lightmapMode")
  20031. ], Light.prototype, "_lightmapMode", void 0);
  20032. return Light;
  20033. }(BABYLON.Node));
  20034. BABYLON.Light = Light;
  20035. })(BABYLON || (BABYLON = {}));
  20036. //# sourceMappingURL=babylon.light.js.map
  20037. "use strict";
  20038. var BABYLON;
  20039. (function (BABYLON) {
  20040. var Camera = /** @class */ (function (_super) {
  20041. __extends(Camera, _super);
  20042. function Camera(name, position, scene) {
  20043. var _this = _super.call(this, name, scene) || this;
  20044. /**
  20045. * The vector the camera should consider as up.
  20046. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20047. */
  20048. _this.upVector = BABYLON.Vector3.Up();
  20049. _this.orthoLeft = null;
  20050. _this.orthoRight = null;
  20051. _this.orthoBottom = null;
  20052. _this.orthoTop = null;
  20053. /**
  20054. * FOV is set in Radians. (default is 0.8)
  20055. */
  20056. _this.fov = 0.8;
  20057. _this.minZ = 1;
  20058. _this.maxZ = 10000.0;
  20059. _this.inertia = 0.9;
  20060. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20061. _this.isIntermediate = false;
  20062. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20063. /**
  20064. * Restricts the camera to viewing objects with the same layerMask.
  20065. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20066. */
  20067. _this.layerMask = 0x0FFFFFFF;
  20068. /**
  20069. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20070. */
  20071. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20072. // Camera rig members
  20073. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20074. _this._rigCameras = new Array();
  20075. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20076. _this._skipRendering = false;
  20077. _this.customRenderTargets = new Array();
  20078. // Observables
  20079. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20080. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20081. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20082. _this.onRestoreStateObservable = new BABYLON.Observable();
  20083. // Cache
  20084. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20085. _this._projectionMatrix = new BABYLON.Matrix();
  20086. _this._doNotComputeProjectionMatrix = false;
  20087. _this._postProcesses = new Array();
  20088. _this._transformMatrix = BABYLON.Matrix.Zero();
  20089. _this._activeMeshes = new BABYLON.SmartArray(256);
  20090. _this._globalPosition = BABYLON.Vector3.Zero();
  20091. _this._refreshFrustumPlanes = true;
  20092. _this.getScene().addCamera(_this);
  20093. if (!_this.getScene().activeCamera) {
  20094. _this.getScene().activeCamera = _this;
  20095. }
  20096. _this.position = position;
  20097. return _this;
  20098. }
  20099. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20100. get: function () {
  20101. return Camera._PERSPECTIVE_CAMERA;
  20102. },
  20103. enumerable: true,
  20104. configurable: true
  20105. });
  20106. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20107. get: function () {
  20108. return Camera._ORTHOGRAPHIC_CAMERA;
  20109. },
  20110. enumerable: true,
  20111. configurable: true
  20112. });
  20113. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20114. /**
  20115. * This is the default FOV mode for perspective cameras.
  20116. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20117. *
  20118. */
  20119. get: function () {
  20120. return Camera._FOVMODE_VERTICAL_FIXED;
  20121. },
  20122. enumerable: true,
  20123. configurable: true
  20124. });
  20125. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20126. /**
  20127. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20128. *
  20129. */
  20130. get: function () {
  20131. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20132. },
  20133. enumerable: true,
  20134. configurable: true
  20135. });
  20136. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20137. get: function () {
  20138. return Camera._RIG_MODE_NONE;
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20144. get: function () {
  20145. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20146. },
  20147. enumerable: true,
  20148. configurable: true
  20149. });
  20150. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20151. get: function () {
  20152. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20153. },
  20154. enumerable: true,
  20155. configurable: true
  20156. });
  20157. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20158. get: function () {
  20159. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20160. },
  20161. enumerable: true,
  20162. configurable: true
  20163. });
  20164. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20165. get: function () {
  20166. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20167. },
  20168. enumerable: true,
  20169. configurable: true
  20170. });
  20171. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20172. get: function () {
  20173. return Camera._RIG_MODE_VR;
  20174. },
  20175. enumerable: true,
  20176. configurable: true
  20177. });
  20178. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20179. get: function () {
  20180. return Camera._RIG_MODE_WEBVR;
  20181. },
  20182. enumerable: true,
  20183. configurable: true
  20184. });
  20185. /**
  20186. * Store current camera state (fov, position, etc..)
  20187. */
  20188. Camera.prototype.storeState = function () {
  20189. this._stateStored = true;
  20190. this._storedFov = this.fov;
  20191. return this;
  20192. };
  20193. /**
  20194. * Restores the camera state values if it has been stored. You must call storeState() first
  20195. */
  20196. Camera.prototype._restoreStateValues = function () {
  20197. if (!this._stateStored) {
  20198. return false;
  20199. }
  20200. this.fov = this._storedFov;
  20201. return true;
  20202. };
  20203. /**
  20204. * Restored camera state. You must call storeState() first
  20205. */
  20206. Camera.prototype.restoreState = function () {
  20207. if (this._restoreStateValues()) {
  20208. this.onRestoreStateObservable.notifyObservers(this);
  20209. return true;
  20210. }
  20211. return false;
  20212. };
  20213. Camera.prototype.getClassName = function () {
  20214. return "Camera";
  20215. };
  20216. /**
  20217. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20218. */
  20219. Camera.prototype.toString = function (fullDetails) {
  20220. var ret = "Name: " + this.name;
  20221. ret += ", type: " + this.getClassName();
  20222. if (this.animations) {
  20223. for (var i = 0; i < this.animations.length; i++) {
  20224. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20225. }
  20226. }
  20227. if (fullDetails) {
  20228. }
  20229. return ret;
  20230. };
  20231. Object.defineProperty(Camera.prototype, "globalPosition", {
  20232. get: function () {
  20233. return this._globalPosition;
  20234. },
  20235. enumerable: true,
  20236. configurable: true
  20237. });
  20238. Camera.prototype.getActiveMeshes = function () {
  20239. return this._activeMeshes;
  20240. };
  20241. Camera.prototype.isActiveMesh = function (mesh) {
  20242. return (this._activeMeshes.indexOf(mesh) !== -1);
  20243. };
  20244. //Cache
  20245. Camera.prototype._initCache = function () {
  20246. _super.prototype._initCache.call(this);
  20247. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20248. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20249. this._cache.mode = undefined;
  20250. this._cache.minZ = undefined;
  20251. this._cache.maxZ = undefined;
  20252. this._cache.fov = undefined;
  20253. this._cache.fovMode = undefined;
  20254. this._cache.aspectRatio = undefined;
  20255. this._cache.orthoLeft = undefined;
  20256. this._cache.orthoRight = undefined;
  20257. this._cache.orthoBottom = undefined;
  20258. this._cache.orthoTop = undefined;
  20259. this._cache.renderWidth = undefined;
  20260. this._cache.renderHeight = undefined;
  20261. };
  20262. Camera.prototype._updateCache = function (ignoreParentClass) {
  20263. if (!ignoreParentClass) {
  20264. _super.prototype._updateCache.call(this);
  20265. }
  20266. this._cache.position.copyFrom(this.position);
  20267. this._cache.upVector.copyFrom(this.upVector);
  20268. };
  20269. // Synchronized
  20270. Camera.prototype._isSynchronized = function () {
  20271. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20272. };
  20273. Camera.prototype._isSynchronizedViewMatrix = function () {
  20274. if (!_super.prototype._isSynchronized.call(this))
  20275. return false;
  20276. return this._cache.position.equals(this.position)
  20277. && this._cache.upVector.equals(this.upVector)
  20278. && this.isSynchronizedWithParent();
  20279. };
  20280. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20281. var check = this._cache.mode === this.mode
  20282. && this._cache.minZ === this.minZ
  20283. && this._cache.maxZ === this.maxZ;
  20284. if (!check) {
  20285. return false;
  20286. }
  20287. var engine = this.getEngine();
  20288. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20289. check = this._cache.fov === this.fov
  20290. && this._cache.fovMode === this.fovMode
  20291. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20292. }
  20293. else {
  20294. check = this._cache.orthoLeft === this.orthoLeft
  20295. && this._cache.orthoRight === this.orthoRight
  20296. && this._cache.orthoBottom === this.orthoBottom
  20297. && this._cache.orthoTop === this.orthoTop
  20298. && this._cache.renderWidth === engine.getRenderWidth()
  20299. && this._cache.renderHeight === engine.getRenderHeight();
  20300. }
  20301. return check;
  20302. };
  20303. // Controls
  20304. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20305. };
  20306. Camera.prototype.detachControl = function (element) {
  20307. };
  20308. Camera.prototype.update = function () {
  20309. this._checkInputs();
  20310. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20311. this._updateRigCameras();
  20312. }
  20313. };
  20314. Camera.prototype._checkInputs = function () {
  20315. this.onAfterCheckInputsObservable.notifyObservers(this);
  20316. };
  20317. Object.defineProperty(Camera.prototype, "rigCameras", {
  20318. get: function () {
  20319. return this._rigCameras;
  20320. },
  20321. enumerable: true,
  20322. configurable: true
  20323. });
  20324. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20325. get: function () {
  20326. return this._rigPostProcess;
  20327. },
  20328. enumerable: true,
  20329. configurable: true
  20330. });
  20331. /**
  20332. * Internal, gets the first post proces.
  20333. * @returns the first post process to be run on this camera.
  20334. */
  20335. Camera.prototype._getFirstPostProcess = function () {
  20336. for (var pp in this._postProcesses) {
  20337. if (this._postProcesses[pp] !== null) {
  20338. return this._postProcesses[pp];
  20339. }
  20340. }
  20341. return null;
  20342. };
  20343. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20344. // invalidate framebuffer
  20345. var firstPostProcess = this._getFirstPostProcess();
  20346. if (firstPostProcess) {
  20347. firstPostProcess.markTextureDirty();
  20348. }
  20349. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20350. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20351. var cam = this._rigCameras[i];
  20352. var rigPostProcess = cam._rigPostProcess;
  20353. // for VR rig, there does not have to be a post process
  20354. if (rigPostProcess) {
  20355. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20356. if (isPass) {
  20357. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20358. cam.isIntermediate = this._postProcesses.length === 0;
  20359. }
  20360. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20361. rigPostProcess.markTextureDirty();
  20362. }
  20363. else {
  20364. cam._postProcesses = this._postProcesses.slice(0);
  20365. }
  20366. }
  20367. };
  20368. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20369. if (insertAt === void 0) { insertAt = null; }
  20370. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20371. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20372. return 0;
  20373. }
  20374. if (insertAt == null || insertAt < 0) {
  20375. this._postProcesses.push(postProcess);
  20376. }
  20377. else if (this._postProcesses[insertAt] === null) {
  20378. this._postProcesses[insertAt] = postProcess;
  20379. }
  20380. else {
  20381. this._postProcesses.splice(insertAt, 0, postProcess);
  20382. }
  20383. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20384. return this._postProcesses.indexOf(postProcess);
  20385. };
  20386. Camera.prototype.detachPostProcess = function (postProcess) {
  20387. var idx = this._postProcesses.indexOf(postProcess);
  20388. if (idx !== -1) {
  20389. this._postProcesses[idx] = null;
  20390. }
  20391. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20392. };
  20393. Camera.prototype.getWorldMatrix = function () {
  20394. if (!this._worldMatrix) {
  20395. this._worldMatrix = BABYLON.Matrix.Identity();
  20396. }
  20397. var viewMatrix = this.getViewMatrix();
  20398. viewMatrix.invertToRef(this._worldMatrix);
  20399. return this._worldMatrix;
  20400. };
  20401. Camera.prototype._getViewMatrix = function () {
  20402. return BABYLON.Matrix.Identity();
  20403. };
  20404. Camera.prototype.getViewMatrix = function (force) {
  20405. if (!force && this._isSynchronizedViewMatrix()) {
  20406. return this._computedViewMatrix;
  20407. }
  20408. this.updateCache();
  20409. this._computedViewMatrix = this._getViewMatrix();
  20410. this._currentRenderId = this.getScene().getRenderId();
  20411. this._refreshFrustumPlanes = true;
  20412. if (!this.parent || !this.parent.getWorldMatrix) {
  20413. this._globalPosition.copyFrom(this.position);
  20414. }
  20415. else {
  20416. if (!this._worldMatrix) {
  20417. this._worldMatrix = BABYLON.Matrix.Identity();
  20418. }
  20419. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20420. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20421. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20422. this._computedViewMatrix.invert();
  20423. this._markSyncedWithParent();
  20424. }
  20425. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20426. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20427. }
  20428. this.onViewMatrixChangedObservable.notifyObservers(this);
  20429. return this._computedViewMatrix;
  20430. };
  20431. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20432. this._doNotComputeProjectionMatrix = true;
  20433. if (projection !== undefined) {
  20434. this._projectionMatrix = projection;
  20435. }
  20436. };
  20437. ;
  20438. Camera.prototype.unfreezeProjectionMatrix = function () {
  20439. this._doNotComputeProjectionMatrix = false;
  20440. };
  20441. ;
  20442. Camera.prototype.getProjectionMatrix = function (force) {
  20443. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20444. return this._projectionMatrix;
  20445. }
  20446. // Cache
  20447. this._cache.mode = this.mode;
  20448. this._cache.minZ = this.minZ;
  20449. this._cache.maxZ = this.maxZ;
  20450. // Matrix
  20451. this._refreshFrustumPlanes = true;
  20452. var engine = this.getEngine();
  20453. var scene = this.getScene();
  20454. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20455. this._cache.fov = this.fov;
  20456. this._cache.fovMode = this.fovMode;
  20457. this._cache.aspectRatio = engine.getAspectRatio(this);
  20458. if (this.minZ <= 0) {
  20459. this.minZ = 0.1;
  20460. }
  20461. if (scene.useRightHandedSystem) {
  20462. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20463. }
  20464. else {
  20465. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20466. }
  20467. }
  20468. else {
  20469. var halfWidth = engine.getRenderWidth() / 2.0;
  20470. var halfHeight = engine.getRenderHeight() / 2.0;
  20471. if (scene.useRightHandedSystem) {
  20472. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20473. }
  20474. else {
  20475. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20476. }
  20477. this._cache.orthoLeft = this.orthoLeft;
  20478. this._cache.orthoRight = this.orthoRight;
  20479. this._cache.orthoBottom = this.orthoBottom;
  20480. this._cache.orthoTop = this.orthoTop;
  20481. this._cache.renderWidth = engine.getRenderWidth();
  20482. this._cache.renderHeight = engine.getRenderHeight();
  20483. }
  20484. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20485. return this._projectionMatrix;
  20486. };
  20487. Camera.prototype.getTranformationMatrix = function () {
  20488. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20489. return this._transformMatrix;
  20490. };
  20491. Camera.prototype.updateFrustumPlanes = function () {
  20492. if (!this._refreshFrustumPlanes) {
  20493. return;
  20494. }
  20495. this.getTranformationMatrix();
  20496. if (!this._frustumPlanes) {
  20497. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20498. }
  20499. else {
  20500. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20501. }
  20502. this._refreshFrustumPlanes = false;
  20503. };
  20504. Camera.prototype.isInFrustum = function (target) {
  20505. this.updateFrustumPlanes();
  20506. return target.isInFrustum(this._frustumPlanes);
  20507. };
  20508. Camera.prototype.isCompletelyInFrustum = function (target) {
  20509. this.updateFrustumPlanes();
  20510. return target.isCompletelyInFrustum(this._frustumPlanes);
  20511. };
  20512. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20513. if (length === void 0) { length = 100; }
  20514. if (!transform) {
  20515. transform = this.getWorldMatrix();
  20516. }
  20517. if (!origin) {
  20518. origin = this.position;
  20519. }
  20520. var forward = new BABYLON.Vector3(0, 0, 1);
  20521. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20522. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20523. return new BABYLON.Ray(origin, direction, length);
  20524. };
  20525. /**
  20526. * Releases resources associated with this node.
  20527. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20528. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20529. */
  20530. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20531. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20532. // Observables
  20533. this.onViewMatrixChangedObservable.clear();
  20534. this.onProjectionMatrixChangedObservable.clear();
  20535. this.onAfterCheckInputsObservable.clear();
  20536. this.onRestoreStateObservable.clear();
  20537. // Inputs
  20538. if (this.inputs) {
  20539. this.inputs.clear();
  20540. }
  20541. // Animations
  20542. this.getScene().stopAnimation(this);
  20543. // Remove from scene
  20544. this.getScene().removeCamera(this);
  20545. while (this._rigCameras.length > 0) {
  20546. var camera = this._rigCameras.pop();
  20547. if (camera) {
  20548. camera.dispose();
  20549. }
  20550. }
  20551. // Postprocesses
  20552. if (this._rigPostProcess) {
  20553. this._rigPostProcess.dispose(this);
  20554. this._rigPostProcess = null;
  20555. this._postProcesses = [];
  20556. }
  20557. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20558. this._rigPostProcess = null;
  20559. this._postProcesses = [];
  20560. }
  20561. else {
  20562. var i = this._postProcesses.length;
  20563. while (--i >= 0) {
  20564. var postProcess = this._postProcesses[i];
  20565. if (postProcess) {
  20566. postProcess.dispose(this);
  20567. }
  20568. }
  20569. }
  20570. // Render targets
  20571. var i = this.customRenderTargets.length;
  20572. while (--i >= 0) {
  20573. this.customRenderTargets[i].dispose();
  20574. }
  20575. this.customRenderTargets = [];
  20576. // Active Meshes
  20577. this._activeMeshes.dispose();
  20578. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20579. };
  20580. Object.defineProperty(Camera.prototype, "leftCamera", {
  20581. // ---- Camera rigs section ----
  20582. get: function () {
  20583. if (this._rigCameras.length < 1) {
  20584. return null;
  20585. }
  20586. return this._rigCameras[0];
  20587. },
  20588. enumerable: true,
  20589. configurable: true
  20590. });
  20591. Object.defineProperty(Camera.prototype, "rightCamera", {
  20592. get: function () {
  20593. if (this._rigCameras.length < 2) {
  20594. return null;
  20595. }
  20596. return this._rigCameras[1];
  20597. },
  20598. enumerable: true,
  20599. configurable: true
  20600. });
  20601. Camera.prototype.getLeftTarget = function () {
  20602. if (this._rigCameras.length < 1) {
  20603. return null;
  20604. }
  20605. return this._rigCameras[0].getTarget();
  20606. };
  20607. Camera.prototype.getRightTarget = function () {
  20608. if (this._rigCameras.length < 2) {
  20609. return null;
  20610. }
  20611. return this._rigCameras[1].getTarget();
  20612. };
  20613. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20614. if (this.cameraRigMode === mode) {
  20615. return;
  20616. }
  20617. while (this._rigCameras.length > 0) {
  20618. var camera = this._rigCameras.pop();
  20619. if (camera) {
  20620. camera.dispose();
  20621. }
  20622. }
  20623. this.cameraRigMode = mode;
  20624. this._cameraRigParams = {};
  20625. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20626. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20627. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20628. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20629. // create the rig cameras, unless none
  20630. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20631. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20632. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20633. if (leftCamera && rightCamera) {
  20634. this._rigCameras.push(leftCamera);
  20635. this._rigCameras.push(rightCamera);
  20636. }
  20637. }
  20638. switch (this.cameraRigMode) {
  20639. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20640. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20641. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20642. break;
  20643. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20644. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20645. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20646. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20647. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20648. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20649. break;
  20650. case Camera.RIG_MODE_VR:
  20651. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20652. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20653. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20654. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20655. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20656. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20657. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20658. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20659. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20660. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20661. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20662. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20663. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20664. if (metrics.compensateDistortion) {
  20665. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20666. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20667. }
  20668. break;
  20669. case Camera.RIG_MODE_WEBVR:
  20670. if (rigParams.vrDisplay) {
  20671. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20672. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20673. //Left eye
  20674. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20675. this._rigCameras[0].setCameraRigParameter("left", true);
  20676. //leaving this for future reference
  20677. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20678. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20679. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20680. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20681. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20682. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20683. this._rigCameras[0].parent = this;
  20684. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20685. //Right eye
  20686. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20687. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20688. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20689. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20690. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20691. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20692. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20693. this._rigCameras[1].parent = this;
  20694. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20695. if (Camera.UseAlternateWebVRRendering) {
  20696. this._rigCameras[1]._skipRendering = true;
  20697. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20698. }
  20699. }
  20700. break;
  20701. }
  20702. this._cascadePostProcessesToRigCams();
  20703. this.update();
  20704. };
  20705. Camera.prototype._getVRProjectionMatrix = function () {
  20706. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20707. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20708. return this._projectionMatrix;
  20709. };
  20710. Camera.prototype._updateCameraRotationMatrix = function () {
  20711. //Here for WebVR
  20712. };
  20713. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20714. //Here for WebVR
  20715. };
  20716. /**
  20717. * This function MUST be overwritten by the different WebVR cameras available.
  20718. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20719. */
  20720. Camera.prototype._getWebVRProjectionMatrix = function () {
  20721. return BABYLON.Matrix.Identity();
  20722. };
  20723. /**
  20724. * This function MUST be overwritten by the different WebVR cameras available.
  20725. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20726. */
  20727. Camera.prototype._getWebVRViewMatrix = function () {
  20728. return BABYLON.Matrix.Identity();
  20729. };
  20730. Camera.prototype.setCameraRigParameter = function (name, value) {
  20731. if (!this._cameraRigParams) {
  20732. this._cameraRigParams = {};
  20733. }
  20734. this._cameraRigParams[name] = value;
  20735. //provisionnally:
  20736. if (name === "interaxialDistance") {
  20737. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20738. }
  20739. };
  20740. /**
  20741. * needs to be overridden by children so sub has required properties to be copied
  20742. */
  20743. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20744. return null;
  20745. };
  20746. /**
  20747. * May need to be overridden by children
  20748. */
  20749. Camera.prototype._updateRigCameras = function () {
  20750. for (var i = 0; i < this._rigCameras.length; i++) {
  20751. this._rigCameras[i].minZ = this.minZ;
  20752. this._rigCameras[i].maxZ = this.maxZ;
  20753. this._rigCameras[i].fov = this.fov;
  20754. }
  20755. // only update viewport when ANAGLYPH
  20756. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20757. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20758. }
  20759. };
  20760. Camera.prototype._setupInputs = function () {
  20761. };
  20762. Camera.prototype.serialize = function () {
  20763. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20764. // Type
  20765. serializationObject.type = this.getClassName();
  20766. // Parent
  20767. if (this.parent) {
  20768. serializationObject.parentId = this.parent.id;
  20769. }
  20770. if (this.inputs) {
  20771. this.inputs.serialize(serializationObject);
  20772. }
  20773. // Animations
  20774. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20775. serializationObject.ranges = this.serializeAnimationRanges();
  20776. return serializationObject;
  20777. };
  20778. Camera.prototype.clone = function (name) {
  20779. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20780. };
  20781. Camera.prototype.getDirection = function (localAxis) {
  20782. var result = BABYLON.Vector3.Zero();
  20783. this.getDirectionToRef(localAxis, result);
  20784. return result;
  20785. };
  20786. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20787. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20788. };
  20789. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20790. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20791. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20792. switch (type) {
  20793. case "ArcRotateCamera":
  20794. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20795. case "DeviceOrientationCamera":
  20796. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20797. case "FollowCamera":
  20798. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20799. case "ArcFollowCamera":
  20800. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20801. case "GamepadCamera":
  20802. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20803. case "TouchCamera":
  20804. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20805. case "VirtualJoysticksCamera":
  20806. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20807. case "WebVRFreeCamera":
  20808. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20809. case "WebVRGamepadCamera":
  20810. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20811. case "VRDeviceOrientationFreeCamera":
  20812. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20813. case "VRDeviceOrientationGamepadCamera":
  20814. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20815. case "AnaglyphArcRotateCamera":
  20816. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20817. case "AnaglyphFreeCamera":
  20818. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20819. case "AnaglyphGamepadCamera":
  20820. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20821. case "AnaglyphUniversalCamera":
  20822. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20823. case "StereoscopicArcRotateCamera":
  20824. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20825. case "StereoscopicFreeCamera":
  20826. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20827. case "StereoscopicGamepadCamera":
  20828. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20829. case "StereoscopicUniversalCamera":
  20830. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20831. case "FreeCamera":// Forcing Universal here
  20832. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20833. default:// Universal Camera is the default value
  20834. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20835. }
  20836. };
  20837. Camera.prototype.computeWorldMatrix = function () {
  20838. return this.getWorldMatrix();
  20839. };
  20840. Camera.Parse = function (parsedCamera, scene) {
  20841. var type = parsedCamera.type;
  20842. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20843. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20844. // Parent
  20845. if (parsedCamera.parentId) {
  20846. camera._waitingParentId = parsedCamera.parentId;
  20847. }
  20848. //If camera has an input manager, let it parse inputs settings
  20849. if (camera.inputs) {
  20850. camera.inputs.parse(parsedCamera);
  20851. camera._setupInputs();
  20852. }
  20853. if (camera.setPosition) {
  20854. camera.position.copyFromFloats(0, 0, 0);
  20855. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20856. }
  20857. // Target
  20858. if (parsedCamera.target) {
  20859. if (camera.setTarget) {
  20860. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20861. }
  20862. }
  20863. // Apply 3d rig, when found
  20864. if (parsedCamera.cameraRigMode) {
  20865. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20866. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20867. }
  20868. // Animations
  20869. if (parsedCamera.animations) {
  20870. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20871. var parsedAnimation = parsedCamera.animations[animationIndex];
  20872. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20873. }
  20874. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20875. }
  20876. if (parsedCamera.autoAnimate) {
  20877. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20878. }
  20879. return camera;
  20880. };
  20881. // Statics
  20882. Camera._PERSPECTIVE_CAMERA = 0;
  20883. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20884. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20885. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20886. Camera._RIG_MODE_NONE = 0;
  20887. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20888. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20889. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20890. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20891. Camera._RIG_MODE_VR = 20;
  20892. Camera._RIG_MODE_WEBVR = 21;
  20893. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20894. Camera.UseAlternateWebVRRendering = false;
  20895. __decorate([
  20896. BABYLON.serializeAsVector3()
  20897. ], Camera.prototype, "position", void 0);
  20898. __decorate([
  20899. BABYLON.serializeAsVector3()
  20900. ], Camera.prototype, "upVector", void 0);
  20901. __decorate([
  20902. BABYLON.serialize()
  20903. ], Camera.prototype, "orthoLeft", void 0);
  20904. __decorate([
  20905. BABYLON.serialize()
  20906. ], Camera.prototype, "orthoRight", void 0);
  20907. __decorate([
  20908. BABYLON.serialize()
  20909. ], Camera.prototype, "orthoBottom", void 0);
  20910. __decorate([
  20911. BABYLON.serialize()
  20912. ], Camera.prototype, "orthoTop", void 0);
  20913. __decorate([
  20914. BABYLON.serialize()
  20915. ], Camera.prototype, "fov", void 0);
  20916. __decorate([
  20917. BABYLON.serialize()
  20918. ], Camera.prototype, "minZ", void 0);
  20919. __decorate([
  20920. BABYLON.serialize()
  20921. ], Camera.prototype, "maxZ", void 0);
  20922. __decorate([
  20923. BABYLON.serialize()
  20924. ], Camera.prototype, "inertia", void 0);
  20925. __decorate([
  20926. BABYLON.serialize()
  20927. ], Camera.prototype, "mode", void 0);
  20928. __decorate([
  20929. BABYLON.serialize()
  20930. ], Camera.prototype, "layerMask", void 0);
  20931. __decorate([
  20932. BABYLON.serialize()
  20933. ], Camera.prototype, "fovMode", void 0);
  20934. __decorate([
  20935. BABYLON.serialize()
  20936. ], Camera.prototype, "cameraRigMode", void 0);
  20937. __decorate([
  20938. BABYLON.serialize()
  20939. ], Camera.prototype, "interaxialDistance", void 0);
  20940. __decorate([
  20941. BABYLON.serialize()
  20942. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20943. return Camera;
  20944. }(BABYLON.Node));
  20945. BABYLON.Camera = Camera;
  20946. })(BABYLON || (BABYLON = {}));
  20947. //# sourceMappingURL=babylon.camera.js.map
  20948. "use strict";
  20949. var BABYLON;
  20950. (function (BABYLON) {
  20951. var RenderingManager = /** @class */ (function () {
  20952. function RenderingManager(scene) {
  20953. this._renderingGroups = new Array();
  20954. this._autoClearDepthStencil = {};
  20955. this._customOpaqueSortCompareFn = {};
  20956. this._customAlphaTestSortCompareFn = {};
  20957. this._customTransparentSortCompareFn = {};
  20958. this._renderinGroupInfo = null;
  20959. this._scene = scene;
  20960. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20961. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20962. }
  20963. }
  20964. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20965. if (depth === void 0) { depth = true; }
  20966. if (stencil === void 0) { stencil = true; }
  20967. if (this._depthStencilBufferAlreadyCleaned) {
  20968. return;
  20969. }
  20970. this._scene.getEngine().clear(null, false, depth, stencil);
  20971. this._depthStencilBufferAlreadyCleaned = true;
  20972. };
  20973. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20974. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20975. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20976. var info = null;
  20977. if (observable) {
  20978. if (!this._renderinGroupInfo) {
  20979. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20980. }
  20981. info = this._renderinGroupInfo;
  20982. info.scene = this._scene;
  20983. info.camera = this._scene.activeCamera;
  20984. }
  20985. // Dispatch sprites
  20986. if (renderSprites) {
  20987. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20988. var manager = this._scene.spriteManagers[index];
  20989. this.dispatchSprites(manager);
  20990. }
  20991. }
  20992. // Render
  20993. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20994. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20995. var renderingGroup = this._renderingGroups[index];
  20996. if (!renderingGroup && !observable)
  20997. continue;
  20998. var renderingGroupMask = 0;
  20999. // Fire PRECLEAR stage
  21000. if (observable && info) {
  21001. renderingGroupMask = Math.pow(2, index);
  21002. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  21003. info.renderingGroupId = index;
  21004. observable.notifyObservers(info, renderingGroupMask);
  21005. }
  21006. // Clear depth/stencil if needed
  21007. if (RenderingManager.AUTOCLEAR) {
  21008. var autoClear = this._autoClearDepthStencil[index];
  21009. if (autoClear && autoClear.autoClear) {
  21010. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  21011. }
  21012. }
  21013. if (observable && info) {
  21014. // Fire PREOPAQUE stage
  21015. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  21016. observable.notifyObservers(info, renderingGroupMask);
  21017. // Fire PRETRANSPARENT stage
  21018. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  21019. observable.notifyObservers(info, renderingGroupMask);
  21020. }
  21021. if (renderingGroup)
  21022. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  21023. // Fire POSTTRANSPARENT stage
  21024. if (observable && info) {
  21025. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  21026. observable.notifyObservers(info, renderingGroupMask);
  21027. }
  21028. }
  21029. };
  21030. RenderingManager.prototype.reset = function () {
  21031. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21032. var renderingGroup = this._renderingGroups[index];
  21033. if (renderingGroup) {
  21034. renderingGroup.prepare();
  21035. }
  21036. }
  21037. };
  21038. RenderingManager.prototype.dispose = function () {
  21039. this.freeRenderingGroups();
  21040. this._renderingGroups.length = 0;
  21041. };
  21042. /**
  21043. * Clear the info related to rendering groups preventing retention points during dispose.
  21044. */
  21045. RenderingManager.prototype.freeRenderingGroups = function () {
  21046. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21047. var renderingGroup = this._renderingGroups[index];
  21048. if (renderingGroup) {
  21049. renderingGroup.dispose();
  21050. }
  21051. }
  21052. };
  21053. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21054. if (this._renderingGroups[renderingGroupId] === undefined) {
  21055. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21056. }
  21057. };
  21058. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21059. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21060. this._prepareRenderingGroup(renderingGroupId);
  21061. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21062. };
  21063. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21064. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21065. this._prepareRenderingGroup(renderingGroupId);
  21066. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21067. };
  21068. /**
  21069. * @param subMesh The submesh to dispatch
  21070. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21071. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21072. */
  21073. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21074. if (mesh === undefined) {
  21075. mesh = subMesh.getMesh();
  21076. }
  21077. var renderingGroupId = mesh.renderingGroupId || 0;
  21078. this._prepareRenderingGroup(renderingGroupId);
  21079. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21080. };
  21081. /**
  21082. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21083. * This allowed control for front to back rendering or reversly depending of the special needs.
  21084. *
  21085. * @param renderingGroupId The rendering group id corresponding to its index
  21086. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21087. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21088. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21089. */
  21090. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21091. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21092. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21093. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21094. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21095. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21096. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21097. if (this._renderingGroups[renderingGroupId]) {
  21098. var group = this._renderingGroups[renderingGroupId];
  21099. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21100. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21101. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21102. }
  21103. };
  21104. /**
  21105. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21106. *
  21107. * @param renderingGroupId The rendering group id corresponding to its index
  21108. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21109. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21110. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21111. */
  21112. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21113. if (depth === void 0) { depth = true; }
  21114. if (stencil === void 0) { stencil = true; }
  21115. this._autoClearDepthStencil[renderingGroupId] = {
  21116. autoClear: autoClearDepthStencil,
  21117. depth: depth,
  21118. stencil: stencil
  21119. };
  21120. };
  21121. /**
  21122. * The max id used for rendering groups (not included)
  21123. */
  21124. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21125. /**
  21126. * The min id used for rendering groups (included)
  21127. */
  21128. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21129. /**
  21130. * Used to globally prevent autoclearing scenes.
  21131. */
  21132. RenderingManager.AUTOCLEAR = true;
  21133. return RenderingManager;
  21134. }());
  21135. BABYLON.RenderingManager = RenderingManager;
  21136. })(BABYLON || (BABYLON = {}));
  21137. //# sourceMappingURL=babylon.renderingManager.js.map
  21138. "use strict";
  21139. var BABYLON;
  21140. (function (BABYLON) {
  21141. var RenderingGroup = /** @class */ (function () {
  21142. /**
  21143. * Creates a new rendering group.
  21144. * @param index The rendering group index
  21145. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21146. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21147. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21148. */
  21149. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21150. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21151. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21152. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21153. this.index = index;
  21154. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21155. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21156. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21157. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21158. this._particleSystems = new BABYLON.SmartArray(256);
  21159. this._spriteManagers = new BABYLON.SmartArray(256);
  21160. this._edgesRenderers = new BABYLON.SmartArray(16);
  21161. this._scene = scene;
  21162. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21163. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21164. this.transparentSortCompareFn = transparentSortCompareFn;
  21165. }
  21166. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21167. /**
  21168. * Set the opaque sort comparison function.
  21169. * If null the sub meshes will be render in the order they were created
  21170. */
  21171. set: function (value) {
  21172. this._opaqueSortCompareFn = value;
  21173. if (value) {
  21174. this._renderOpaque = this.renderOpaqueSorted;
  21175. }
  21176. else {
  21177. this._renderOpaque = RenderingGroup.renderUnsorted;
  21178. }
  21179. },
  21180. enumerable: true,
  21181. configurable: true
  21182. });
  21183. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21184. /**
  21185. * Set the alpha test sort comparison function.
  21186. * If null the sub meshes will be render in the order they were created
  21187. */
  21188. set: function (value) {
  21189. this._alphaTestSortCompareFn = value;
  21190. if (value) {
  21191. this._renderAlphaTest = this.renderAlphaTestSorted;
  21192. }
  21193. else {
  21194. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21195. }
  21196. },
  21197. enumerable: true,
  21198. configurable: true
  21199. });
  21200. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21201. /**
  21202. * Set the transparent sort comparison function.
  21203. * If null the sub meshes will be render in the order they were created
  21204. */
  21205. set: function (value) {
  21206. if (value) {
  21207. this._transparentSortCompareFn = value;
  21208. }
  21209. else {
  21210. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21211. }
  21212. this._renderTransparent = this.renderTransparentSorted;
  21213. },
  21214. enumerable: true,
  21215. configurable: true
  21216. });
  21217. /**
  21218. * Render all the sub meshes contained in the group.
  21219. * @param customRenderFunction Used to override the default render behaviour of the group.
  21220. * @returns true if rendered some submeshes.
  21221. */
  21222. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21223. if (customRenderFunction) {
  21224. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21225. return;
  21226. }
  21227. var engine = this._scene.getEngine();
  21228. // Depth only
  21229. if (this._depthOnlySubMeshes.length !== 0) {
  21230. engine.setColorWrite(false);
  21231. this._renderAlphaTest(this._depthOnlySubMeshes);
  21232. engine.setColorWrite(true);
  21233. }
  21234. // Opaque
  21235. if (this._opaqueSubMeshes.length !== 0) {
  21236. this._renderOpaque(this._opaqueSubMeshes);
  21237. }
  21238. // Alpha test
  21239. if (this._alphaTestSubMeshes.length !== 0) {
  21240. this._renderAlphaTest(this._alphaTestSubMeshes);
  21241. }
  21242. var stencilState = engine.getStencilBuffer();
  21243. engine.setStencilBuffer(false);
  21244. // Sprites
  21245. if (renderSprites) {
  21246. this._renderSprites();
  21247. }
  21248. // Particles
  21249. if (renderParticles) {
  21250. this._renderParticles(activeMeshes);
  21251. }
  21252. if (this.onBeforeTransparentRendering) {
  21253. this.onBeforeTransparentRendering();
  21254. }
  21255. // Transparent
  21256. if (this._transparentSubMeshes.length !== 0) {
  21257. this._renderTransparent(this._transparentSubMeshes);
  21258. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21259. }
  21260. // Set back stencil to false in case it changes before the edge renderer.
  21261. engine.setStencilBuffer(false);
  21262. // Edges
  21263. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21264. this._edgesRenderers.data[edgesRendererIndex].render();
  21265. }
  21266. // Restore Stencil state.
  21267. engine.setStencilBuffer(stencilState);
  21268. };
  21269. /**
  21270. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21271. * @param subMeshes The submeshes to render
  21272. */
  21273. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21274. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21275. };
  21276. /**
  21277. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21278. * @param subMeshes The submeshes to render
  21279. */
  21280. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21281. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21282. };
  21283. /**
  21284. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21285. * @param subMeshes The submeshes to render
  21286. */
  21287. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21288. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21289. };
  21290. /**
  21291. * Renders the submeshes in a specified order.
  21292. * @param subMeshes The submeshes to sort before render
  21293. * @param sortCompareFn The comparison function use to sort
  21294. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21295. * @param transparent Specifies to activate blending if true
  21296. */
  21297. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21298. var subIndex = 0;
  21299. var subMesh;
  21300. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21301. for (; subIndex < subMeshes.length; subIndex++) {
  21302. subMesh = subMeshes.data[subIndex];
  21303. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21304. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21305. }
  21306. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21307. if (sortCompareFn) {
  21308. sortedArray.sort(sortCompareFn);
  21309. }
  21310. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21311. subMesh = sortedArray[subIndex];
  21312. if (transparent) {
  21313. var material = subMesh.getMaterial();
  21314. if (material && material.needDepthPrePass) {
  21315. var engine = material.getScene().getEngine();
  21316. engine.setColorWrite(false);
  21317. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21318. subMesh.render(false);
  21319. engine.setColorWrite(true);
  21320. }
  21321. }
  21322. subMesh.render(transparent);
  21323. }
  21324. };
  21325. /**
  21326. * Renders the submeshes in the order they were dispatched (no sort applied).
  21327. * @param subMeshes The submeshes to render
  21328. */
  21329. RenderingGroup.renderUnsorted = function (subMeshes) {
  21330. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21331. var submesh = subMeshes.data[subIndex];
  21332. submesh.render(false);
  21333. }
  21334. };
  21335. /**
  21336. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21337. * are rendered back to front if in the same alpha index.
  21338. *
  21339. * @param a The first submesh
  21340. * @param b The second submesh
  21341. * @returns The result of the comparison
  21342. */
  21343. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21344. // Alpha index first
  21345. if (a._alphaIndex > b._alphaIndex) {
  21346. return 1;
  21347. }
  21348. if (a._alphaIndex < b._alphaIndex) {
  21349. return -1;
  21350. }
  21351. // Then distance to camera
  21352. return RenderingGroup.backToFrontSortCompare(a, b);
  21353. };
  21354. /**
  21355. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21356. * are rendered back to front.
  21357. *
  21358. * @param a The first submesh
  21359. * @param b The second submesh
  21360. * @returns The result of the comparison
  21361. */
  21362. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21363. // Then distance to camera
  21364. if (a._distanceToCamera < b._distanceToCamera) {
  21365. return 1;
  21366. }
  21367. if (a._distanceToCamera > b._distanceToCamera) {
  21368. return -1;
  21369. }
  21370. return 0;
  21371. };
  21372. /**
  21373. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21374. * are rendered front to back (prevent overdraw).
  21375. *
  21376. * @param a The first submesh
  21377. * @param b The second submesh
  21378. * @returns The result of the comparison
  21379. */
  21380. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21381. // Then distance to camera
  21382. if (a._distanceToCamera < b._distanceToCamera) {
  21383. return -1;
  21384. }
  21385. if (a._distanceToCamera > b._distanceToCamera) {
  21386. return 1;
  21387. }
  21388. return 0;
  21389. };
  21390. /**
  21391. * Resets the different lists of submeshes to prepare a new frame.
  21392. */
  21393. RenderingGroup.prototype.prepare = function () {
  21394. this._opaqueSubMeshes.reset();
  21395. this._transparentSubMeshes.reset();
  21396. this._alphaTestSubMeshes.reset();
  21397. this._depthOnlySubMeshes.reset();
  21398. this._particleSystems.reset();
  21399. this._spriteManagers.reset();
  21400. this._edgesRenderers.reset();
  21401. };
  21402. RenderingGroup.prototype.dispose = function () {
  21403. this._opaqueSubMeshes.dispose();
  21404. this._transparentSubMeshes.dispose();
  21405. this._alphaTestSubMeshes.dispose();
  21406. this._depthOnlySubMeshes.dispose();
  21407. this._particleSystems.dispose();
  21408. this._spriteManagers.dispose();
  21409. this._edgesRenderers.dispose();
  21410. };
  21411. /**
  21412. * Inserts the submesh in its correct queue depending on its material.
  21413. * @param subMesh The submesh to dispatch
  21414. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21415. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21416. */
  21417. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21418. // Get mesh and materials if not provided
  21419. if (mesh === undefined) {
  21420. mesh = subMesh.getMesh();
  21421. }
  21422. if (material === undefined) {
  21423. material = subMesh.getMaterial();
  21424. }
  21425. if (material === null || material === undefined) {
  21426. return;
  21427. }
  21428. if (material.needAlphaBlendingForMesh(mesh)) {
  21429. this._transparentSubMeshes.push(subMesh);
  21430. }
  21431. else if (material.needAlphaTesting()) {
  21432. if (material.needDepthPrePass) {
  21433. this._depthOnlySubMeshes.push(subMesh);
  21434. }
  21435. this._alphaTestSubMeshes.push(subMesh);
  21436. }
  21437. else {
  21438. if (material.needDepthPrePass) {
  21439. this._depthOnlySubMeshes.push(subMesh);
  21440. }
  21441. this._opaqueSubMeshes.push(subMesh); // Opaque
  21442. }
  21443. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21444. this._edgesRenderers.push(mesh._edgesRenderer);
  21445. }
  21446. };
  21447. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21448. this._spriteManagers.push(spriteManager);
  21449. };
  21450. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21451. this._particleSystems.push(particleSystem);
  21452. };
  21453. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21454. if (this._particleSystems.length === 0) {
  21455. return;
  21456. }
  21457. // Particles
  21458. var activeCamera = this._scene.activeCamera;
  21459. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21460. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21461. var particleSystem = this._particleSystems.data[particleIndex];
  21462. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21463. continue;
  21464. }
  21465. var emitter = particleSystem.emitter;
  21466. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21467. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21468. }
  21469. }
  21470. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21471. };
  21472. RenderingGroup.prototype._renderSprites = function () {
  21473. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21474. return;
  21475. }
  21476. // Sprites
  21477. var activeCamera = this._scene.activeCamera;
  21478. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21479. for (var id = 0; id < this._spriteManagers.length; id++) {
  21480. var spriteManager = this._spriteManagers.data[id];
  21481. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21482. spriteManager.render();
  21483. }
  21484. }
  21485. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21486. };
  21487. return RenderingGroup;
  21488. }());
  21489. BABYLON.RenderingGroup = RenderingGroup;
  21490. })(BABYLON || (BABYLON = {}));
  21491. //# sourceMappingURL=babylon.renderingGroup.js.map
  21492. "use strict";
  21493. var BABYLON;
  21494. (function (BABYLON) {
  21495. var ClickInfo = /** @class */ (function () {
  21496. function ClickInfo() {
  21497. this._singleClick = false;
  21498. this._doubleClick = false;
  21499. this._hasSwiped = false;
  21500. this._ignore = false;
  21501. }
  21502. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21503. get: function () {
  21504. return this._singleClick;
  21505. },
  21506. set: function (b) {
  21507. this._singleClick = b;
  21508. },
  21509. enumerable: true,
  21510. configurable: true
  21511. });
  21512. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21513. get: function () {
  21514. return this._doubleClick;
  21515. },
  21516. set: function (b) {
  21517. this._doubleClick = b;
  21518. },
  21519. enumerable: true,
  21520. configurable: true
  21521. });
  21522. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21523. get: function () {
  21524. return this._hasSwiped;
  21525. },
  21526. set: function (b) {
  21527. this._hasSwiped = b;
  21528. },
  21529. enumerable: true,
  21530. configurable: true
  21531. });
  21532. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21533. get: function () {
  21534. return this._ignore;
  21535. },
  21536. set: function (b) {
  21537. this._ignore = b;
  21538. },
  21539. enumerable: true,
  21540. configurable: true
  21541. });
  21542. return ClickInfo;
  21543. }());
  21544. /**
  21545. * This class is used by the onRenderingGroupObservable
  21546. */
  21547. var RenderingGroupInfo = /** @class */ (function () {
  21548. function RenderingGroupInfo() {
  21549. }
  21550. /**
  21551. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21552. * This stage will be fired no matter what
  21553. */
  21554. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21555. /**
  21556. * Called before opaque object are rendered.
  21557. * This stage will be fired only if there's 3D Opaque content to render
  21558. */
  21559. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21560. /**
  21561. * Called after the opaque objects are rendered and before the transparent ones
  21562. * This stage will be fired only if there's 3D transparent content to render
  21563. */
  21564. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21565. /**
  21566. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21567. * This stage will be fired no matter what
  21568. */
  21569. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21570. return RenderingGroupInfo;
  21571. }());
  21572. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21573. /**
  21574. * Represents a scene to be rendered by the engine.
  21575. * @see http://doc.babylonjs.com/page.php?p=21911
  21576. */
  21577. var Scene = /** @class */ (function () {
  21578. /**
  21579. * @constructor
  21580. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21581. */
  21582. function Scene(engine) {
  21583. // Members
  21584. this.autoClear = true;
  21585. this.autoClearDepthAndStencil = true;
  21586. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21587. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21588. this._forceWireframe = false;
  21589. this._forcePointsCloud = false;
  21590. this.forceShowBoundingBoxes = false;
  21591. this.animationsEnabled = true;
  21592. this.useConstantAnimationDeltaTime = false;
  21593. this.constantlyUpdateMeshUnderPointer = false;
  21594. this.hoverCursor = "pointer";
  21595. this.defaultCursor = "";
  21596. /**
  21597. * This is used to call preventDefault() on pointer down
  21598. * in order to block unwanted artifacts like system double clicks
  21599. */
  21600. this.preventDefaultOnPointerDown = true;
  21601. // Metadata
  21602. this.metadata = null;
  21603. /**
  21604. * An event triggered when the scene is disposed.
  21605. * @type {BABYLON.Observable}
  21606. */
  21607. this.onDisposeObservable = new BABYLON.Observable();
  21608. this._onDisposeObserver = null;
  21609. /**
  21610. * An event triggered before rendering the scene (right after animations and physics)
  21611. * @type {BABYLON.Observable}
  21612. */
  21613. this.onBeforeRenderObservable = new BABYLON.Observable();
  21614. this._onBeforeRenderObserver = null;
  21615. /**
  21616. * An event triggered after rendering the scene
  21617. * @type {BABYLON.Observable}
  21618. */
  21619. this.onAfterRenderObservable = new BABYLON.Observable();
  21620. this._onAfterRenderObserver = null;
  21621. /**
  21622. * An event triggered before animating the scene
  21623. * @type {BABYLON.Observable}
  21624. */
  21625. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21626. /**
  21627. * An event triggered after animations processing
  21628. * @type {BABYLON.Observable}
  21629. */
  21630. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21631. /**
  21632. * An event triggered before draw calls are ready to be sent
  21633. * @type {BABYLON.Observable}
  21634. */
  21635. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21636. /**
  21637. * An event triggered after draw calls have been sent
  21638. * @type {BABYLON.Observable}
  21639. */
  21640. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21641. /**
  21642. * An event triggered when physic simulation is about to be run
  21643. * @type {BABYLON.Observable}
  21644. */
  21645. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21646. /**
  21647. * An event triggered when physic simulation has been done
  21648. * @type {BABYLON.Observable}
  21649. */
  21650. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21651. /**
  21652. * An event triggered when the scene is ready
  21653. * @type {BABYLON.Observable}
  21654. */
  21655. this.onReadyObservable = new BABYLON.Observable();
  21656. /**
  21657. * An event triggered before rendering a camera
  21658. * @type {BABYLON.Observable}
  21659. */
  21660. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21661. this._onBeforeCameraRenderObserver = null;
  21662. /**
  21663. * An event triggered after rendering a camera
  21664. * @type {BABYLON.Observable}
  21665. */
  21666. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21667. this._onAfterCameraRenderObserver = null;
  21668. /**
  21669. * An event triggered when active meshes evaluation is about to start
  21670. * @type {BABYLON.Observable}
  21671. */
  21672. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21673. /**
  21674. * An event triggered when active meshes evaluation is done
  21675. * @type {BABYLON.Observable}
  21676. */
  21677. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21678. /**
  21679. * An event triggered when particles rendering is about to start
  21680. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21681. * @type {BABYLON.Observable}
  21682. */
  21683. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21684. /**
  21685. * An event triggered when particles rendering is done
  21686. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21687. * @type {BABYLON.Observable}
  21688. */
  21689. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21690. /**
  21691. * An event triggered when sprites rendering is about to start
  21692. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21693. * @type {BABYLON.Observable}
  21694. */
  21695. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21696. /**
  21697. * An event triggered when sprites rendering is done
  21698. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21699. * @type {BABYLON.Observable}
  21700. */
  21701. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21702. /**
  21703. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21704. * @type {BABYLON.Observable}
  21705. */
  21706. this.onDataLoadedObservable = new BABYLON.Observable();
  21707. /**
  21708. * An event triggered when a camera is created
  21709. * @type {BABYLON.Observable}
  21710. */
  21711. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21712. /**
  21713. * An event triggered when a camera is removed
  21714. * @type {BABYLON.Observable}
  21715. */
  21716. this.onCameraRemovedObservable = new BABYLON.Observable();
  21717. /**
  21718. * An event triggered when a light is created
  21719. * @type {BABYLON.Observable}
  21720. */
  21721. this.onNewLightAddedObservable = new BABYLON.Observable();
  21722. /**
  21723. * An event triggered when a light is removed
  21724. * @type {BABYLON.Observable}
  21725. */
  21726. this.onLightRemovedObservable = new BABYLON.Observable();
  21727. /**
  21728. * An event triggered when a geometry is created
  21729. * @type {BABYLON.Observable}
  21730. */
  21731. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21732. /**
  21733. * An event triggered when a geometry is removed
  21734. * @type {BABYLON.Observable}
  21735. */
  21736. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21737. /**
  21738. * An event triggered when a transform node is created
  21739. * @type {BABYLON.Observable}
  21740. */
  21741. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21742. /**
  21743. * An event triggered when a transform node is removed
  21744. * @type {BABYLON.Observable}
  21745. */
  21746. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21747. /**
  21748. * An event triggered when a mesh is created
  21749. * @type {BABYLON.Observable}
  21750. */
  21751. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21752. /**
  21753. * An event triggered when a mesh is removed
  21754. * @type {BABYLON.Observable}
  21755. */
  21756. this.onMeshRemovedObservable = new BABYLON.Observable();
  21757. /**
  21758. * An event triggered when render targets are about to be rendered
  21759. * Can happen multiple times per frame.
  21760. * @type {BABYLON.Observable}
  21761. */
  21762. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21763. /**
  21764. * An event triggered when render targets were rendered.
  21765. * Can happen multiple times per frame.
  21766. * @type {BABYLON.Observable}
  21767. */
  21768. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21769. /**
  21770. * An event triggered before calculating deterministic simulation step
  21771. * @type {BABYLON.Observable}
  21772. */
  21773. this.onBeforeStepObservable = new BABYLON.Observable();
  21774. /**
  21775. * An event triggered after calculating deterministic simulation step
  21776. * @type {BABYLON.Observable}
  21777. */
  21778. this.onAfterStepObservable = new BABYLON.Observable();
  21779. /**
  21780. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21781. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21782. * 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)
  21783. */
  21784. this.onRenderingGroupObservable = new BABYLON.Observable();
  21785. // Animations
  21786. this.animations = [];
  21787. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21788. /**
  21789. * 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).
  21790. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21791. */
  21792. this.onPrePointerObservable = new BABYLON.Observable();
  21793. /**
  21794. * Observable event triggered each time an input event is received from the rendering canvas
  21795. */
  21796. this.onPointerObservable = new BABYLON.Observable();
  21797. this._meshPickProceed = false;
  21798. this._currentPickResult = null;
  21799. this._previousPickResult = null;
  21800. this._totalPointersPressed = 0;
  21801. this._doubleClickOccured = false;
  21802. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21803. this.cameraToUseForPointers = null;
  21804. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21805. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21806. this._startingPointerTime = 0;
  21807. this._previousStartingPointerTime = 0;
  21808. // Deterministic lockstep
  21809. this._timeAccumulator = 0;
  21810. this._currentStepId = 0;
  21811. this._currentInternalStep = 0;
  21812. // Keyboard
  21813. /**
  21814. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21815. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21816. */
  21817. this.onPreKeyboardObservable = new BABYLON.Observable();
  21818. /**
  21819. * Observable event triggered each time an keyboard event is received from the hosting window
  21820. */
  21821. this.onKeyboardObservable = new BABYLON.Observable();
  21822. // Coordinate system
  21823. /**
  21824. * use right-handed coordinate system on this scene.
  21825. * @type {boolean}
  21826. */
  21827. this._useRightHandedSystem = false;
  21828. // Fog
  21829. this._fogEnabled = true;
  21830. this._fogMode = Scene.FOGMODE_NONE;
  21831. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21832. this.fogDensity = 0.1;
  21833. this.fogStart = 0;
  21834. this.fogEnd = 1000.0;
  21835. // Lights
  21836. /**
  21837. * is shadow enabled on this scene.
  21838. * @type {boolean}
  21839. */
  21840. this._shadowsEnabled = true;
  21841. /**
  21842. * is light enabled on this scene.
  21843. * @type {boolean}
  21844. */
  21845. this._lightsEnabled = true;
  21846. /**
  21847. * All of the lights added to this scene.
  21848. * @see BABYLON.Light
  21849. * @type {BABYLON.Light[]}
  21850. */
  21851. this.lights = new Array();
  21852. // Cameras
  21853. /** All of the cameras added to this scene. */
  21854. this.cameras = new Array();
  21855. /** All of the active cameras added to this scene. */
  21856. this.activeCameras = new Array();
  21857. // Meshes
  21858. /**
  21859. * All of the tranform nodes added to this scene.
  21860. * @see BABYLON.TransformNode
  21861. * @type {BABYLON.TransformNode[]}
  21862. */
  21863. this.transformNodes = new Array();
  21864. /**
  21865. * All of the (abstract) meshes added to this scene.
  21866. * @see BABYLON.AbstractMesh
  21867. * @type {BABYLON.AbstractMesh[]}
  21868. */
  21869. this.meshes = new Array();
  21870. /**
  21871. * All of the animation groups added to this scene.
  21872. * @see BABYLON.AnimationGroup
  21873. * @type {BABYLON.AnimationGroup[]}
  21874. */
  21875. this.animationGroups = new Array();
  21876. // Geometries
  21877. this._geometries = new Array();
  21878. this.materials = new Array();
  21879. this.multiMaterials = new Array();
  21880. // Textures
  21881. this._texturesEnabled = true;
  21882. this.textures = new Array();
  21883. // Particles
  21884. this.particlesEnabled = true;
  21885. this.particleSystems = new Array();
  21886. // Sprites
  21887. this.spritesEnabled = true;
  21888. this.spriteManagers = new Array();
  21889. /**
  21890. * The list of layers (background and foreground) of the scene.
  21891. */
  21892. this.layers = new Array();
  21893. /**
  21894. * The list of effect layers (highlights/glow) contained in the scene.
  21895. */
  21896. this.effectLayers = new Array();
  21897. // Skeletons
  21898. this._skeletonsEnabled = true;
  21899. this.skeletons = new Array();
  21900. // Morph targets
  21901. this.morphTargetManagers = new Array();
  21902. // Lens flares
  21903. this.lensFlaresEnabled = true;
  21904. this.lensFlareSystems = new Array();
  21905. // Collisions
  21906. this.collisionsEnabled = true;
  21907. /** Defines the gravity applied to this scene */
  21908. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21909. // Postprocesses
  21910. this.postProcesses = new Array();
  21911. this.postProcessesEnabled = true;
  21912. // Customs render targets
  21913. this.renderTargetsEnabled = true;
  21914. this.dumpNextRenderTargets = false;
  21915. this.customRenderTargets = new Array();
  21916. // Imported meshes
  21917. this.importedMeshesFiles = new Array();
  21918. // Probes
  21919. this.probesEnabled = true;
  21920. this.reflectionProbes = new Array();
  21921. this._actionManagers = new Array();
  21922. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21923. // Procedural textures
  21924. this.proceduralTexturesEnabled = true;
  21925. this._proceduralTextures = new Array();
  21926. this.soundTracks = new Array();
  21927. this._audioEnabled = true;
  21928. this._headphone = false;
  21929. // Performance counters
  21930. this._totalVertices = new BABYLON.PerfCounter();
  21931. this._activeIndices = new BABYLON.PerfCounter();
  21932. this._activeParticles = new BABYLON.PerfCounter();
  21933. this._activeBones = new BABYLON.PerfCounter();
  21934. this._animationTime = 0;
  21935. this.animationTimeScale = 1;
  21936. this._renderId = 0;
  21937. this._executeWhenReadyTimeoutId = -1;
  21938. this._intermediateRendering = false;
  21939. this._viewUpdateFlag = -1;
  21940. this._projectionUpdateFlag = -1;
  21941. this._alternateViewUpdateFlag = -1;
  21942. this._alternateProjectionUpdateFlag = -1;
  21943. this._toBeDisposed = new BABYLON.SmartArray(256);
  21944. this._activeRequests = new Array();
  21945. this._pendingData = new Array();
  21946. this._isDisposed = false;
  21947. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21948. this._activeMeshes = new BABYLON.SmartArray(256);
  21949. this._processedMaterials = new BABYLON.SmartArray(256);
  21950. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21951. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21952. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21953. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21954. this._activeAnimatables = new Array();
  21955. this._transformMatrix = BABYLON.Matrix.Zero();
  21956. this._useAlternateCameraConfiguration = false;
  21957. this._alternateRendering = false;
  21958. this.requireLightSorting = false;
  21959. this._depthRenderer = {};
  21960. this._activeMeshesFrozen = false;
  21961. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21962. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21963. this._engine.scenes.push(this);
  21964. this._uid = null;
  21965. this._renderingManager = new BABYLON.RenderingManager(this);
  21966. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21967. if (BABYLON.OutlineRenderer) {
  21968. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21969. }
  21970. if (BABYLON.Tools.IsWindowObjectExist()) {
  21971. this.attachControl();
  21972. }
  21973. //simplification queue
  21974. if (BABYLON.SimplificationQueue) {
  21975. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21976. }
  21977. //collision coordinator initialization. For now legacy per default.
  21978. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21979. // Uniform Buffer
  21980. this._createUbo();
  21981. // Default Image processing definition.
  21982. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21983. }
  21984. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21985. /** The fog is deactivated */
  21986. get: function () {
  21987. return Scene._FOGMODE_NONE;
  21988. },
  21989. enumerable: true,
  21990. configurable: true
  21991. });
  21992. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21993. /** The fog density is following an exponential function */
  21994. get: function () {
  21995. return Scene._FOGMODE_EXP;
  21996. },
  21997. enumerable: true,
  21998. configurable: true
  21999. });
  22000. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  22001. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  22002. get: function () {
  22003. return Scene._FOGMODE_EXP2;
  22004. },
  22005. enumerable: true,
  22006. configurable: true
  22007. });
  22008. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  22009. /** The fog density is following a linear function. */
  22010. get: function () {
  22011. return Scene._FOGMODE_LINEAR;
  22012. },
  22013. enumerable: true,
  22014. configurable: true
  22015. });
  22016. Object.defineProperty(Scene.prototype, "environmentTexture", {
  22017. /**
  22018. * Texture used in all pbr material as the reflection texture.
  22019. * As in the majority of the scene they are the same (exception for multi room and so on),
  22020. * this is easier to reference from here than from all the materials.
  22021. */
  22022. get: function () {
  22023. return this._environmentTexture;
  22024. },
  22025. /**
  22026. * Texture used in all pbr material as the reflection texture.
  22027. * As in the majority of the scene they are the same (exception for multi room and so on),
  22028. * this is easier to set here than in all the materials.
  22029. */
  22030. set: function (value) {
  22031. if (this._environmentTexture === value) {
  22032. return;
  22033. }
  22034. this._environmentTexture = value;
  22035. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22036. },
  22037. enumerable: true,
  22038. configurable: true
  22039. });
  22040. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22041. /**
  22042. * Default image processing configuration used either in the rendering
  22043. * Forward main pass or through the imageProcessingPostProcess if present.
  22044. * As in the majority of the scene they are the same (exception for multi camera),
  22045. * this is easier to reference from here than from all the materials and post process.
  22046. *
  22047. * No setter as we it is a shared configuration, you can set the values instead.
  22048. */
  22049. get: function () {
  22050. return this._imageProcessingConfiguration;
  22051. },
  22052. enumerable: true,
  22053. configurable: true
  22054. });
  22055. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22056. get: function () {
  22057. return this._forceWireframe;
  22058. },
  22059. set: function (value) {
  22060. if (this._forceWireframe === value) {
  22061. return;
  22062. }
  22063. this._forceWireframe = value;
  22064. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22065. },
  22066. enumerable: true,
  22067. configurable: true
  22068. });
  22069. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22070. get: function () {
  22071. return this._forcePointsCloud;
  22072. },
  22073. set: function (value) {
  22074. if (this._forcePointsCloud === value) {
  22075. return;
  22076. }
  22077. this._forcePointsCloud = value;
  22078. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22079. },
  22080. enumerable: true,
  22081. configurable: true
  22082. });
  22083. Object.defineProperty(Scene.prototype, "onDispose", {
  22084. /** A function to be executed when this scene is disposed. */
  22085. set: function (callback) {
  22086. if (this._onDisposeObserver) {
  22087. this.onDisposeObservable.remove(this._onDisposeObserver);
  22088. }
  22089. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22090. },
  22091. enumerable: true,
  22092. configurable: true
  22093. });
  22094. Object.defineProperty(Scene.prototype, "beforeRender", {
  22095. /** A function to be executed before rendering this scene */
  22096. set: function (callback) {
  22097. if (this._onBeforeRenderObserver) {
  22098. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22099. }
  22100. if (callback) {
  22101. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22102. }
  22103. },
  22104. enumerable: true,
  22105. configurable: true
  22106. });
  22107. Object.defineProperty(Scene.prototype, "afterRender", {
  22108. /** A function to be executed after rendering this scene */
  22109. set: function (callback) {
  22110. if (this._onAfterRenderObserver) {
  22111. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22112. }
  22113. if (callback) {
  22114. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22115. }
  22116. },
  22117. enumerable: true,
  22118. configurable: true
  22119. });
  22120. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22121. set: function (callback) {
  22122. if (this._onBeforeCameraRenderObserver) {
  22123. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22124. }
  22125. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22126. },
  22127. enumerable: true,
  22128. configurable: true
  22129. });
  22130. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22131. set: function (callback) {
  22132. if (this._onAfterCameraRenderObserver) {
  22133. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22134. }
  22135. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22136. },
  22137. enumerable: true,
  22138. configurable: true
  22139. });
  22140. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22141. get: function () {
  22142. if (!this._gamepadManager) {
  22143. this._gamepadManager = new BABYLON.GamepadManager(this);
  22144. }
  22145. return this._gamepadManager;
  22146. },
  22147. enumerable: true,
  22148. configurable: true
  22149. });
  22150. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22151. get: function () {
  22152. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22153. },
  22154. enumerable: true,
  22155. configurable: true
  22156. });
  22157. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22158. get: function () {
  22159. return this._useRightHandedSystem;
  22160. },
  22161. set: function (value) {
  22162. if (this._useRightHandedSystem === value) {
  22163. return;
  22164. }
  22165. this._useRightHandedSystem = value;
  22166. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22167. },
  22168. enumerable: true,
  22169. configurable: true
  22170. });
  22171. Scene.prototype.setStepId = function (newStepId) {
  22172. this._currentStepId = newStepId;
  22173. };
  22174. ;
  22175. Scene.prototype.getStepId = function () {
  22176. return this._currentStepId;
  22177. };
  22178. ;
  22179. Scene.prototype.getInternalStep = function () {
  22180. return this._currentInternalStep;
  22181. };
  22182. ;
  22183. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22184. get: function () {
  22185. return this._fogEnabled;
  22186. },
  22187. /**
  22188. * is fog enabled on this scene.
  22189. */
  22190. set: function (value) {
  22191. if (this._fogEnabled === value) {
  22192. return;
  22193. }
  22194. this._fogEnabled = value;
  22195. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22196. },
  22197. enumerable: true,
  22198. configurable: true
  22199. });
  22200. Object.defineProperty(Scene.prototype, "fogMode", {
  22201. get: function () {
  22202. return this._fogMode;
  22203. },
  22204. set: function (value) {
  22205. if (this._fogMode === value) {
  22206. return;
  22207. }
  22208. this._fogMode = value;
  22209. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22210. },
  22211. enumerable: true,
  22212. configurable: true
  22213. });
  22214. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22215. get: function () {
  22216. return this._shadowsEnabled;
  22217. },
  22218. set: function (value) {
  22219. if (this._shadowsEnabled === value) {
  22220. return;
  22221. }
  22222. this._shadowsEnabled = value;
  22223. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22224. },
  22225. enumerable: true,
  22226. configurable: true
  22227. });
  22228. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22229. get: function () {
  22230. return this._lightsEnabled;
  22231. },
  22232. set: function (value) {
  22233. if (this._lightsEnabled === value) {
  22234. return;
  22235. }
  22236. this._lightsEnabled = value;
  22237. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22238. },
  22239. enumerable: true,
  22240. configurable: true
  22241. });
  22242. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22243. /** The default material used on meshes when no material is affected */
  22244. get: function () {
  22245. if (!this._defaultMaterial) {
  22246. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22247. }
  22248. return this._defaultMaterial;
  22249. },
  22250. /** The default material used on meshes when no material is affected */
  22251. set: function (value) {
  22252. this._defaultMaterial = value;
  22253. },
  22254. enumerable: true,
  22255. configurable: true
  22256. });
  22257. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22258. get: function () {
  22259. return this._texturesEnabled;
  22260. },
  22261. set: function (value) {
  22262. if (this._texturesEnabled === value) {
  22263. return;
  22264. }
  22265. this._texturesEnabled = value;
  22266. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22272. get: function () {
  22273. return this._skeletonsEnabled;
  22274. },
  22275. set: function (value) {
  22276. if (this._skeletonsEnabled === value) {
  22277. return;
  22278. }
  22279. this._skeletonsEnabled = value;
  22280. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22281. },
  22282. enumerable: true,
  22283. configurable: true
  22284. });
  22285. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22286. get: function () {
  22287. if (!this._postProcessRenderPipelineManager) {
  22288. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22289. }
  22290. return this._postProcessRenderPipelineManager;
  22291. },
  22292. enumerable: true,
  22293. configurable: true
  22294. });
  22295. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22296. get: function () {
  22297. if (!this._mainSoundTrack) {
  22298. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22299. }
  22300. return this._mainSoundTrack;
  22301. },
  22302. enumerable: true,
  22303. configurable: true
  22304. });
  22305. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22306. get: function () {
  22307. return this._alternateRendering;
  22308. },
  22309. enumerable: true,
  22310. configurable: true
  22311. });
  22312. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22313. get: function () {
  22314. return this._frustumPlanes;
  22315. },
  22316. enumerable: true,
  22317. configurable: true
  22318. });
  22319. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22320. /**
  22321. * Gets the current geometry buffer associated to the scene.
  22322. */
  22323. get: function () {
  22324. return this._geometryBufferRenderer;
  22325. },
  22326. /**
  22327. * Sets the current geometry buffer for the scene.
  22328. */
  22329. set: function (geometryBufferRenderer) {
  22330. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22331. this._geometryBufferRenderer = geometryBufferRenderer;
  22332. }
  22333. },
  22334. enumerable: true,
  22335. configurable: true
  22336. });
  22337. Object.defineProperty(Scene.prototype, "debugLayer", {
  22338. // Properties
  22339. get: function () {
  22340. if (!this._debugLayer) {
  22341. this._debugLayer = new BABYLON.DebugLayer(this);
  22342. }
  22343. return this._debugLayer;
  22344. },
  22345. enumerable: true,
  22346. configurable: true
  22347. });
  22348. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22349. get: function () {
  22350. return this._workerCollisions;
  22351. },
  22352. set: function (enabled) {
  22353. if (!BABYLON.CollisionCoordinatorLegacy) {
  22354. return;
  22355. }
  22356. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22357. this._workerCollisions = enabled;
  22358. if (this.collisionCoordinator) {
  22359. this.collisionCoordinator.destroy();
  22360. }
  22361. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22362. this.collisionCoordinator.init(this);
  22363. },
  22364. enumerable: true,
  22365. configurable: true
  22366. });
  22367. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22368. get: function () {
  22369. return this._selectionOctree;
  22370. },
  22371. enumerable: true,
  22372. configurable: true
  22373. });
  22374. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22375. /**
  22376. * The mesh that is currently under the pointer.
  22377. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22378. */
  22379. get: function () {
  22380. return this._pointerOverMesh;
  22381. },
  22382. enumerable: true,
  22383. configurable: true
  22384. });
  22385. Object.defineProperty(Scene.prototype, "pointerX", {
  22386. /**
  22387. * Current on-screen X position of the pointer
  22388. * @return {number} X position of the pointer
  22389. */
  22390. get: function () {
  22391. return this._pointerX;
  22392. },
  22393. enumerable: true,
  22394. configurable: true
  22395. });
  22396. Object.defineProperty(Scene.prototype, "pointerY", {
  22397. /**
  22398. * Current on-screen Y position of the pointer
  22399. * @return {number} Y position of the pointer
  22400. */
  22401. get: function () {
  22402. return this._pointerY;
  22403. },
  22404. enumerable: true,
  22405. configurable: true
  22406. });
  22407. Scene.prototype.getCachedMaterial = function () {
  22408. return this._cachedMaterial;
  22409. };
  22410. Scene.prototype.getCachedEffect = function () {
  22411. return this._cachedEffect;
  22412. };
  22413. Scene.prototype.getCachedVisibility = function () {
  22414. return this._cachedVisibility;
  22415. };
  22416. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22417. if (visibility === void 0) { visibility = 1; }
  22418. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22419. };
  22420. Scene.prototype.getBoundingBoxRenderer = function () {
  22421. if (!this._boundingBoxRenderer) {
  22422. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22423. }
  22424. return this._boundingBoxRenderer;
  22425. };
  22426. Scene.prototype.getOutlineRenderer = function () {
  22427. return this._outlineRenderer;
  22428. };
  22429. Scene.prototype.getEngine = function () {
  22430. return this._engine;
  22431. };
  22432. Scene.prototype.getTotalVertices = function () {
  22433. return this._totalVertices.current;
  22434. };
  22435. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22436. get: function () {
  22437. return this._totalVertices;
  22438. },
  22439. enumerable: true,
  22440. configurable: true
  22441. });
  22442. Scene.prototype.getActiveIndices = function () {
  22443. return this._activeIndices.current;
  22444. };
  22445. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22446. get: function () {
  22447. return this._activeIndices;
  22448. },
  22449. enumerable: true,
  22450. configurable: true
  22451. });
  22452. Scene.prototype.getActiveParticles = function () {
  22453. return this._activeParticles.current;
  22454. };
  22455. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22456. get: function () {
  22457. return this._activeParticles;
  22458. },
  22459. enumerable: true,
  22460. configurable: true
  22461. });
  22462. Scene.prototype.getActiveBones = function () {
  22463. return this._activeBones.current;
  22464. };
  22465. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22466. get: function () {
  22467. return this._activeBones;
  22468. },
  22469. enumerable: true,
  22470. configurable: true
  22471. });
  22472. // Stats
  22473. Scene.prototype.getInterFramePerfCounter = function () {
  22474. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22475. return 0;
  22476. };
  22477. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22478. get: function () {
  22479. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22480. return null;
  22481. },
  22482. enumerable: true,
  22483. configurable: true
  22484. });
  22485. Scene.prototype.getLastFrameDuration = function () {
  22486. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22487. return 0;
  22488. };
  22489. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22490. get: function () {
  22491. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22492. return null;
  22493. },
  22494. enumerable: true,
  22495. configurable: true
  22496. });
  22497. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22498. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22499. return 0;
  22500. };
  22501. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22502. get: function () {
  22503. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22504. return null;
  22505. },
  22506. enumerable: true,
  22507. configurable: true
  22508. });
  22509. Scene.prototype.getActiveMeshes = function () {
  22510. return this._activeMeshes;
  22511. };
  22512. Scene.prototype.getRenderTargetsDuration = function () {
  22513. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22514. return 0;
  22515. };
  22516. Scene.prototype.getRenderDuration = function () {
  22517. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22518. return 0;
  22519. };
  22520. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22521. get: function () {
  22522. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22523. return null;
  22524. },
  22525. enumerable: true,
  22526. configurable: true
  22527. });
  22528. Scene.prototype.getParticlesDuration = function () {
  22529. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22530. return 0;
  22531. };
  22532. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22533. get: function () {
  22534. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22535. return null;
  22536. },
  22537. enumerable: true,
  22538. configurable: true
  22539. });
  22540. Scene.prototype.getSpritesDuration = function () {
  22541. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22542. return 0;
  22543. };
  22544. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22545. get: function () {
  22546. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22547. return null;
  22548. },
  22549. enumerable: true,
  22550. configurable: true
  22551. });
  22552. Scene.prototype.getAnimationRatio = function () {
  22553. return this._animationRatio;
  22554. };
  22555. Scene.prototype.getRenderId = function () {
  22556. return this._renderId;
  22557. };
  22558. Scene.prototype.incrementRenderId = function () {
  22559. this._renderId++;
  22560. };
  22561. Scene.prototype._updatePointerPosition = function (evt) {
  22562. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22563. if (!canvasRect) {
  22564. return;
  22565. }
  22566. this._pointerX = evt.clientX - canvasRect.left;
  22567. this._pointerY = evt.clientY - canvasRect.top;
  22568. this._unTranslatedPointerX = this._pointerX;
  22569. this._unTranslatedPointerY = this._pointerY;
  22570. };
  22571. Scene.prototype._createUbo = function () {
  22572. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22573. this._sceneUbo.addUniform("viewProjection", 16);
  22574. this._sceneUbo.addUniform("view", 16);
  22575. };
  22576. Scene.prototype._createAlternateUbo = function () {
  22577. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22578. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22579. this._alternateSceneUbo.addUniform("view", 16);
  22580. };
  22581. // Pointers handling
  22582. /**
  22583. * Use this method to simulate a pointer move on a mesh
  22584. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22585. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22586. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22587. */
  22588. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22589. var evt = new PointerEvent("pointermove", pointerEventInit);
  22590. return this._processPointerMove(pickResult, evt);
  22591. };
  22592. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22593. var canvas = this._engine.getRenderingCanvas();
  22594. if (!canvas) {
  22595. return this;
  22596. }
  22597. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22598. this.setPointerOverSprite(null);
  22599. this.setPointerOverMesh(pickResult.pickedMesh);
  22600. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22601. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22602. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22603. }
  22604. else {
  22605. canvas.style.cursor = this.hoverCursor;
  22606. }
  22607. }
  22608. else {
  22609. canvas.style.cursor = this.defaultCursor;
  22610. }
  22611. }
  22612. else {
  22613. this.setPointerOverMesh(null);
  22614. // Sprites
  22615. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22616. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22617. this.setPointerOverSprite(pickResult.pickedSprite);
  22618. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22619. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22620. }
  22621. else {
  22622. canvas.style.cursor = this.hoverCursor;
  22623. }
  22624. }
  22625. else {
  22626. this.setPointerOverSprite(null);
  22627. // Restore pointer
  22628. canvas.style.cursor = this.defaultCursor;
  22629. }
  22630. }
  22631. if (pickResult) {
  22632. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22633. if (this.onPointerMove) {
  22634. this.onPointerMove(evt, pickResult, type);
  22635. }
  22636. if (this.onPointerObservable.hasObservers()) {
  22637. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22638. this.onPointerObservable.notifyObservers(pi, type);
  22639. }
  22640. }
  22641. return this;
  22642. };
  22643. /**
  22644. * Use this method to simulate a pointer down on a mesh
  22645. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22646. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22647. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22648. */
  22649. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22650. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22651. return this._processPointerDown(pickResult, evt);
  22652. };
  22653. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22654. var _this = this;
  22655. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22656. this._pickedDownMesh = pickResult.pickedMesh;
  22657. var actionManager = pickResult.pickedMesh.actionManager;
  22658. if (actionManager) {
  22659. if (actionManager.hasPickTriggers) {
  22660. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22661. switch (evt.button) {
  22662. case 0:
  22663. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22664. break;
  22665. case 1:
  22666. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22667. break;
  22668. case 2:
  22669. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22670. break;
  22671. }
  22672. }
  22673. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22674. window.setTimeout(function () {
  22675. 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);
  22676. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22677. if (_this._totalPointersPressed !== 0 &&
  22678. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22679. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22680. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22681. _this._startingPointerTime = 0;
  22682. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22683. }
  22684. }
  22685. }, Scene.LongPressDelay);
  22686. }
  22687. }
  22688. }
  22689. if (pickResult) {
  22690. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22691. if (this.onPointerDown) {
  22692. this.onPointerDown(evt, pickResult, type);
  22693. }
  22694. if (this.onPointerObservable.hasObservers()) {
  22695. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22696. this.onPointerObservable.notifyObservers(pi, type);
  22697. }
  22698. }
  22699. return this;
  22700. };
  22701. /**
  22702. * Use this method to simulate a pointer up on a mesh
  22703. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22704. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22705. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22706. */
  22707. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22708. var evt = new PointerEvent("pointerup", pointerEventInit);
  22709. var clickInfo = new ClickInfo();
  22710. clickInfo.singleClick = true;
  22711. clickInfo.ignore = true;
  22712. return this._processPointerUp(pickResult, evt, clickInfo);
  22713. };
  22714. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22715. if (pickResult && pickResult && pickResult.pickedMesh) {
  22716. this._pickedUpMesh = pickResult.pickedMesh;
  22717. if (this._pickedDownMesh === this._pickedUpMesh) {
  22718. if (this.onPointerPick) {
  22719. this.onPointerPick(evt, pickResult);
  22720. }
  22721. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22722. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22723. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22724. this.onPointerObservable.notifyObservers(pi, type_1);
  22725. }
  22726. }
  22727. if (pickResult.pickedMesh.actionManager) {
  22728. if (clickInfo.ignore) {
  22729. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22730. }
  22731. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22732. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22733. }
  22734. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22735. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22736. }
  22737. }
  22738. }
  22739. if (this._pickedDownMesh &&
  22740. this._pickedDownMesh.actionManager &&
  22741. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22742. this._pickedDownMesh !== this._pickedUpMesh) {
  22743. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22744. }
  22745. var type = BABYLON.PointerEventTypes.POINTERUP;
  22746. if (this.onPointerObservable.hasObservers()) {
  22747. if (!clickInfo.ignore) {
  22748. if (!clickInfo.hasSwiped) {
  22749. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22750. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22751. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22752. this.onPointerObservable.notifyObservers(pi, type_2);
  22753. }
  22754. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22755. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22756. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22757. this.onPointerObservable.notifyObservers(pi, type_3);
  22758. }
  22759. }
  22760. }
  22761. else {
  22762. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22763. this.onPointerObservable.notifyObservers(pi, type);
  22764. }
  22765. }
  22766. if (this.onPointerUp) {
  22767. this.onPointerUp(evt, pickResult, type);
  22768. }
  22769. return this;
  22770. };
  22771. /**
  22772. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22773. * @param attachUp defines if you want to attach events to pointerup
  22774. * @param attachDown defines if you want to attach events to pointerdown
  22775. * @param attachMove defines if you want to attach events to pointermove
  22776. */
  22777. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22778. var _this = this;
  22779. if (attachUp === void 0) { attachUp = true; }
  22780. if (attachDown === void 0) { attachDown = true; }
  22781. if (attachMove === void 0) { attachMove = true; }
  22782. this._initActionManager = function (act, clickInfo) {
  22783. if (!_this._meshPickProceed) {
  22784. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22785. _this._currentPickResult = pickResult;
  22786. if (pickResult) {
  22787. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22788. }
  22789. _this._meshPickProceed = true;
  22790. }
  22791. return act;
  22792. };
  22793. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22794. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22795. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22796. btn !== _this._previousButtonPressed) {
  22797. _this._doubleClickOccured = false;
  22798. clickInfo.singleClick = true;
  22799. clickInfo.ignore = false;
  22800. cb(clickInfo, _this._currentPickResult);
  22801. }
  22802. };
  22803. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22804. var clickInfo = new ClickInfo();
  22805. _this._currentPickResult = null;
  22806. var act = null;
  22807. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22808. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22809. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22810. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22811. act = _this._initActionManager(act, clickInfo);
  22812. if (act)
  22813. checkPicking = act.hasPickTriggers;
  22814. }
  22815. if (checkPicking) {
  22816. var btn = evt.button;
  22817. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22818. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22819. if (!clickInfo.hasSwiped) {
  22820. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22821. if (!checkSingleClickImmediately) {
  22822. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22823. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22824. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22825. act = _this._initActionManager(act, clickInfo);
  22826. if (act)
  22827. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22828. }
  22829. }
  22830. if (checkSingleClickImmediately) {
  22831. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22832. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22833. btn !== _this._previousButtonPressed) {
  22834. clickInfo.singleClick = true;
  22835. cb(clickInfo, _this._currentPickResult);
  22836. }
  22837. }
  22838. else {
  22839. // wait that no double click has been raised during the double click delay
  22840. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22841. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22842. }
  22843. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22844. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22845. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22846. act = _this._initActionManager(act, clickInfo);
  22847. if (act)
  22848. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22849. }
  22850. if (checkDoubleClick) {
  22851. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22852. if (btn === _this._previousButtonPressed &&
  22853. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22854. !_this._doubleClickOccured) {
  22855. // pointer has not moved for 2 clicks, it's a double click
  22856. if (!clickInfo.hasSwiped &&
  22857. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22858. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22859. _this._previousStartingPointerTime = 0;
  22860. _this._doubleClickOccured = true;
  22861. clickInfo.doubleClick = true;
  22862. clickInfo.ignore = false;
  22863. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22864. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22865. }
  22866. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22867. cb(clickInfo, _this._currentPickResult);
  22868. }
  22869. else {
  22870. _this._doubleClickOccured = false;
  22871. _this._previousStartingPointerTime = _this._startingPointerTime;
  22872. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22873. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22874. _this._previousButtonPressed = btn;
  22875. if (Scene.ExclusiveDoubleClickMode) {
  22876. if (_this._previousDelayedSimpleClickTimeout) {
  22877. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22878. }
  22879. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22880. cb(clickInfo, _this._previousPickResult);
  22881. }
  22882. else {
  22883. cb(clickInfo, _this._currentPickResult);
  22884. }
  22885. }
  22886. }
  22887. else {
  22888. _this._doubleClickOccured = false;
  22889. _this._previousStartingPointerTime = _this._startingPointerTime;
  22890. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22891. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22892. _this._previousButtonPressed = btn;
  22893. }
  22894. }
  22895. }
  22896. }
  22897. clickInfo.ignore = true;
  22898. cb(clickInfo, _this._currentPickResult);
  22899. };
  22900. this._spritePredicate = function (sprite) {
  22901. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22902. };
  22903. this._onPointerMove = function (evt) {
  22904. _this._updatePointerPosition(evt);
  22905. // PreObservable support
  22906. if (_this.onPrePointerObservable.hasObservers()) {
  22907. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22908. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22909. _this.onPrePointerObservable.notifyObservers(pi, type);
  22910. if (pi.skipOnPointerObservable) {
  22911. return;
  22912. }
  22913. }
  22914. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22915. return;
  22916. }
  22917. if (!_this.pointerMovePredicate) {
  22918. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22919. }
  22920. // Meshes
  22921. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22922. _this._processPointerMove(pickResult, evt);
  22923. };
  22924. this._onPointerDown = function (evt) {
  22925. _this._totalPointersPressed++;
  22926. _this._pickedDownMesh = null;
  22927. _this._meshPickProceed = false;
  22928. _this._updatePointerPosition(evt);
  22929. if (_this.preventDefaultOnPointerDown && canvas) {
  22930. evt.preventDefault();
  22931. canvas.focus();
  22932. }
  22933. // PreObservable support
  22934. if (_this.onPrePointerObservable.hasObservers()) {
  22935. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22936. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22937. _this.onPrePointerObservable.notifyObservers(pi, type);
  22938. if (pi.skipOnPointerObservable) {
  22939. return;
  22940. }
  22941. }
  22942. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22943. return;
  22944. }
  22945. _this._startingPointerPosition.x = _this._pointerX;
  22946. _this._startingPointerPosition.y = _this._pointerY;
  22947. _this._startingPointerTime = new Date().getTime();
  22948. if (!_this.pointerDownPredicate) {
  22949. _this.pointerDownPredicate = function (mesh) {
  22950. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22951. };
  22952. }
  22953. // Meshes
  22954. _this._pickedDownMesh = null;
  22955. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22956. _this._processPointerDown(pickResult, evt);
  22957. // Sprites
  22958. _this._pickedDownSprite = null;
  22959. if (_this.spriteManagers.length > 0) {
  22960. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22961. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22962. if (pickResult.pickedSprite.actionManager) {
  22963. _this._pickedDownSprite = pickResult.pickedSprite;
  22964. switch (evt.button) {
  22965. case 0:
  22966. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22967. break;
  22968. case 1:
  22969. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22970. break;
  22971. case 2:
  22972. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22973. break;
  22974. }
  22975. if (pickResult.pickedSprite.actionManager) {
  22976. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22977. }
  22978. }
  22979. }
  22980. }
  22981. };
  22982. this._onPointerUp = function (evt) {
  22983. if (_this._totalPointersPressed === 0) {
  22984. return; // So we need to test it the pointer down was pressed before.
  22985. }
  22986. _this._totalPointersPressed--;
  22987. _this._pickedUpMesh = null;
  22988. _this._meshPickProceed = false;
  22989. _this._updatePointerPosition(evt);
  22990. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22991. // PreObservable support
  22992. if (_this.onPrePointerObservable.hasObservers()) {
  22993. if (!clickInfo.ignore) {
  22994. if (!clickInfo.hasSwiped) {
  22995. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22996. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22997. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22998. _this.onPrePointerObservable.notifyObservers(pi, type);
  22999. if (pi.skipOnPointerObservable) {
  23000. return;
  23001. }
  23002. }
  23003. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  23004. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  23005. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23006. _this.onPrePointerObservable.notifyObservers(pi, type);
  23007. if (pi.skipOnPointerObservable) {
  23008. return;
  23009. }
  23010. }
  23011. }
  23012. }
  23013. else {
  23014. var type = BABYLON.PointerEventTypes.POINTERUP;
  23015. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23016. _this.onPrePointerObservable.notifyObservers(pi, type);
  23017. if (pi.skipOnPointerObservable) {
  23018. return;
  23019. }
  23020. }
  23021. }
  23022. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23023. return;
  23024. }
  23025. if (!_this.pointerUpPredicate) {
  23026. _this.pointerUpPredicate = function (mesh) {
  23027. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23028. };
  23029. }
  23030. // Meshes
  23031. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23032. _this._initActionManager(null, clickInfo);
  23033. }
  23034. if (!pickResult) {
  23035. pickResult = _this._currentPickResult;
  23036. }
  23037. _this._processPointerUp(pickResult, evt, clickInfo);
  23038. // Sprites
  23039. if (_this.spriteManagers.length > 0) {
  23040. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23041. if (spritePickResult) {
  23042. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23043. if (spritePickResult.pickedSprite.actionManager) {
  23044. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23045. if (spritePickResult.pickedSprite.actionManager) {
  23046. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23047. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23048. }
  23049. }
  23050. }
  23051. }
  23052. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23053. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23054. }
  23055. }
  23056. }
  23057. _this._previousPickResult = _this._currentPickResult;
  23058. });
  23059. };
  23060. this._onKeyDown = function (evt) {
  23061. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23062. if (_this.onPreKeyboardObservable.hasObservers()) {
  23063. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23064. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23065. if (pi.skipOnPointerObservable) {
  23066. return;
  23067. }
  23068. }
  23069. if (_this.onKeyboardObservable.hasObservers()) {
  23070. var pi = new BABYLON.KeyboardInfo(type, evt);
  23071. _this.onKeyboardObservable.notifyObservers(pi, type);
  23072. }
  23073. if (_this.actionManager) {
  23074. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23075. }
  23076. };
  23077. this._onKeyUp = function (evt) {
  23078. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23079. if (_this.onPreKeyboardObservable.hasObservers()) {
  23080. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23081. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23082. if (pi.skipOnPointerObservable) {
  23083. return;
  23084. }
  23085. }
  23086. if (_this.onKeyboardObservable.hasObservers()) {
  23087. var pi = new BABYLON.KeyboardInfo(type, evt);
  23088. _this.onKeyboardObservable.notifyObservers(pi, type);
  23089. }
  23090. if (_this.actionManager) {
  23091. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23092. }
  23093. };
  23094. var engine = this.getEngine();
  23095. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23096. if (!canvas) {
  23097. return;
  23098. }
  23099. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23100. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23101. });
  23102. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23103. if (!canvas) {
  23104. return;
  23105. }
  23106. canvas.removeEventListener("keydown", _this._onKeyDown);
  23107. canvas.removeEventListener("keyup", _this._onKeyUp);
  23108. });
  23109. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23110. var canvas = this._engine.getRenderingCanvas();
  23111. if (!canvas) {
  23112. return;
  23113. }
  23114. if (attachMove) {
  23115. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23116. // Wheel
  23117. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23118. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23119. }
  23120. if (attachDown) {
  23121. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23122. }
  23123. if (attachUp) {
  23124. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23125. }
  23126. canvas.tabIndex = 1;
  23127. };
  23128. Scene.prototype.detachControl = function () {
  23129. var engine = this.getEngine();
  23130. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23131. var canvas = engine.getRenderingCanvas();
  23132. if (!canvas) {
  23133. return;
  23134. }
  23135. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23136. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23137. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23138. if (this._onCanvasBlurObserver) {
  23139. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23140. }
  23141. if (this._onCanvasFocusObserver) {
  23142. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23143. }
  23144. // Wheel
  23145. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23146. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23147. // Keyboard
  23148. canvas.removeEventListener("keydown", this._onKeyDown);
  23149. canvas.removeEventListener("keyup", this._onKeyUp);
  23150. // Observables
  23151. this.onKeyboardObservable.clear();
  23152. this.onPreKeyboardObservable.clear();
  23153. this.onPointerObservable.clear();
  23154. this.onPrePointerObservable.clear();
  23155. };
  23156. /**
  23157. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23158. * Delay loaded resources are not taking in account
  23159. * @return true if all required resources are ready
  23160. */
  23161. Scene.prototype.isReady = function () {
  23162. if (this._isDisposed) {
  23163. return false;
  23164. }
  23165. if (this._pendingData.length > 0) {
  23166. return false;
  23167. }
  23168. var index;
  23169. var engine = this.getEngine();
  23170. // Geometries
  23171. for (index = 0; index < this._geometries.length; index++) {
  23172. var geometry = this._geometries[index];
  23173. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23174. return false;
  23175. }
  23176. }
  23177. // Meshes
  23178. for (index = 0; index < this.meshes.length; index++) {
  23179. var mesh = this.meshes[index];
  23180. if (!mesh.isEnabled()) {
  23181. continue;
  23182. }
  23183. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23184. continue;
  23185. }
  23186. if (!mesh.isReady(true)) {
  23187. return false;
  23188. }
  23189. // Effect layers
  23190. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23191. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23192. var layer = _a[_i];
  23193. if (!layer.hasMesh(mesh)) {
  23194. continue;
  23195. }
  23196. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23197. var subMesh = _c[_b];
  23198. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23199. return false;
  23200. }
  23201. }
  23202. }
  23203. }
  23204. // Particles
  23205. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23206. var particleSystem = _e[_d];
  23207. if (!particleSystem.isReady()) {
  23208. return false;
  23209. }
  23210. }
  23211. return true;
  23212. };
  23213. Scene.prototype.resetCachedMaterial = function () {
  23214. this._cachedMaterial = null;
  23215. this._cachedEffect = null;
  23216. this._cachedVisibility = null;
  23217. };
  23218. Scene.prototype.registerBeforeRender = function (func) {
  23219. this.onBeforeRenderObservable.add(func);
  23220. };
  23221. Scene.prototype.unregisterBeforeRender = function (func) {
  23222. this.onBeforeRenderObservable.removeCallback(func);
  23223. };
  23224. Scene.prototype.registerAfterRender = function (func) {
  23225. this.onAfterRenderObservable.add(func);
  23226. };
  23227. Scene.prototype.unregisterAfterRender = function (func) {
  23228. this.onAfterRenderObservable.removeCallback(func);
  23229. };
  23230. Scene.prototype._executeOnceBeforeRender = function (func) {
  23231. var _this = this;
  23232. var execFunc = function () {
  23233. func();
  23234. setTimeout(function () {
  23235. _this.unregisterBeforeRender(execFunc);
  23236. });
  23237. };
  23238. this.registerBeforeRender(execFunc);
  23239. };
  23240. /**
  23241. * The provided function will run before render once and will be disposed afterwards.
  23242. * A timeout delay can be provided so that the function will be executed in N ms.
  23243. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23244. * @param func The function to be executed.
  23245. * @param timeout optional delay in ms
  23246. */
  23247. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23248. var _this = this;
  23249. if (timeout !== undefined) {
  23250. setTimeout(function () {
  23251. _this._executeOnceBeforeRender(func);
  23252. }, timeout);
  23253. }
  23254. else {
  23255. this._executeOnceBeforeRender(func);
  23256. }
  23257. };
  23258. Scene.prototype._addPendingData = function (data) {
  23259. this._pendingData.push(data);
  23260. };
  23261. Scene.prototype._removePendingData = function (data) {
  23262. var wasLoading = this.isLoading;
  23263. var index = this._pendingData.indexOf(data);
  23264. if (index !== -1) {
  23265. this._pendingData.splice(index, 1);
  23266. }
  23267. if (wasLoading && !this.isLoading) {
  23268. this.onDataLoadedObservable.notifyObservers(this);
  23269. }
  23270. };
  23271. Scene.prototype.getWaitingItemsCount = function () {
  23272. return this._pendingData.length;
  23273. };
  23274. Object.defineProperty(Scene.prototype, "isLoading", {
  23275. get: function () {
  23276. return this._pendingData.length > 0;
  23277. },
  23278. enumerable: true,
  23279. configurable: true
  23280. });
  23281. /**
  23282. * Registers a function to be executed when the scene is ready.
  23283. * @param {Function} func - the function to be executed.
  23284. */
  23285. Scene.prototype.executeWhenReady = function (func) {
  23286. var _this = this;
  23287. this.onReadyObservable.add(func);
  23288. if (this._executeWhenReadyTimeoutId !== -1) {
  23289. return;
  23290. }
  23291. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23292. _this._checkIsReady();
  23293. }, 150);
  23294. };
  23295. /**
  23296. * Returns a promise that resolves when the scene is ready.
  23297. * @returns A promise that resolves when the scene is ready.
  23298. */
  23299. Scene.prototype.whenReadyAsync = function () {
  23300. var _this = this;
  23301. return new Promise(function (resolve) {
  23302. _this.executeWhenReady(function () {
  23303. resolve();
  23304. });
  23305. });
  23306. };
  23307. Scene.prototype._checkIsReady = function () {
  23308. var _this = this;
  23309. if (this.isReady()) {
  23310. this.onReadyObservable.notifyObservers(this);
  23311. this.onReadyObservable.clear();
  23312. this._executeWhenReadyTimeoutId = -1;
  23313. return;
  23314. }
  23315. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23316. _this._checkIsReady();
  23317. }, 150);
  23318. };
  23319. // Animations
  23320. /**
  23321. * Will start the animation sequence of a given target
  23322. * @param target defines the target
  23323. * @param from defines from which frame should animation start
  23324. * @param to defines until which frame should animation run.
  23325. * @param weight defines the weight to apply to the animation (1.0 by default)
  23326. * @param loop defines if the animation loops
  23327. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23328. * @param onAnimationEnd defines the function to be executed when the animation ends
  23329. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23330. * @returns the animatable object created for this animation
  23331. * @see BABYLON.Animatable
  23332. */
  23333. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23334. if (weight === void 0) { weight = 1.0; }
  23335. if (speedRatio === void 0) { speedRatio = 1.0; }
  23336. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23337. returnedAnimatable.weight = weight;
  23338. return returnedAnimatable;
  23339. };
  23340. /**
  23341. * Will start the animation sequence of a given target
  23342. * @param target defines the target
  23343. * @param from defines from which frame should animation start
  23344. * @param to defines until which frame should animation run.
  23345. * @param loop defines if the animation loops
  23346. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23347. * @param onAnimationEnd defines the function to be executed when the animation ends
  23348. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23349. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23350. * @returns the animatable object created for this animation
  23351. * @see BABYLON.Animatable
  23352. */
  23353. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23354. if (speedRatio === void 0) { speedRatio = 1.0; }
  23355. if (stopCurrent === void 0) { stopCurrent = true; }
  23356. if (from > to && speedRatio > 0) {
  23357. speedRatio *= -1;
  23358. }
  23359. if (stopCurrent) {
  23360. this.stopAnimation(target);
  23361. }
  23362. if (!animatable) {
  23363. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23364. }
  23365. // Local animations
  23366. if (target.animations) {
  23367. animatable.appendAnimations(target, target.animations);
  23368. }
  23369. // Children animations
  23370. if (target.getAnimatables) {
  23371. var animatables = target.getAnimatables();
  23372. for (var index = 0; index < animatables.length; index++) {
  23373. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23374. }
  23375. }
  23376. animatable.reset();
  23377. return animatable;
  23378. };
  23379. /**
  23380. * Begin a new animation on a given node
  23381. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23382. * @param {BABYLON.Animation[]} defines the list of animations to start
  23383. * @param {number} from defines the initial value
  23384. * @param {number} to defines the final value
  23385. * @param {boolean} loop defines if you want animation to loop (off by default)
  23386. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23387. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23388. * @returns the list of created animatables
  23389. */
  23390. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23391. if (speedRatio === undefined) {
  23392. speedRatio = 1.0;
  23393. }
  23394. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23395. return animatable;
  23396. };
  23397. /**
  23398. * Begin a new animation on a given node and its hierarchy
  23399. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23400. * @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.
  23401. * @param {BABYLON.Animation[]} defines the list of animations to start
  23402. * @param {number} from defines the initial value
  23403. * @param {number} to defines the final value
  23404. * @param {boolean} loop defines if you want animation to loop (off by default)
  23405. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23406. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23407. * @returns the list of animatables created for all nodes
  23408. */
  23409. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23410. var children = target.getDescendants(directDescendantsOnly);
  23411. var result = [];
  23412. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23413. var child = children_1[_i];
  23414. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23415. }
  23416. return result;
  23417. };
  23418. Scene.prototype.getAnimatableByTarget = function (target) {
  23419. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23420. if (this._activeAnimatables[index].target === target) {
  23421. return this._activeAnimatables[index];
  23422. }
  23423. }
  23424. return null;
  23425. };
  23426. /**
  23427. * Gets all animatables associated with a given target
  23428. * @param target defines the target to look animatables for
  23429. * @returns an array of Animatables
  23430. */
  23431. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23432. var result = [];
  23433. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23434. if (this._activeAnimatables[index].target === target) {
  23435. result.push(this._activeAnimatables[index]);
  23436. }
  23437. }
  23438. return result;
  23439. };
  23440. Object.defineProperty(Scene.prototype, "animatables", {
  23441. get: function () {
  23442. return this._activeAnimatables;
  23443. },
  23444. enumerable: true,
  23445. configurable: true
  23446. });
  23447. /**
  23448. * Will stop the animation of the given target
  23449. * @param target - the target
  23450. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23451. * @see beginAnimation
  23452. */
  23453. Scene.prototype.stopAnimation = function (target, animationName) {
  23454. var animatables = this.getAllAnimatablesByTarget(target);
  23455. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23456. var animatable = animatables_1[_i];
  23457. animatable.stop(animationName);
  23458. }
  23459. };
  23460. /**
  23461. * Stops and removes all animations that have been applied to the scene
  23462. */
  23463. Scene.prototype.stopAllAnimations = function () {
  23464. if (this._activeAnimatables) {
  23465. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23466. this._activeAnimatables[i].stop();
  23467. }
  23468. this._activeAnimatables = [];
  23469. }
  23470. };
  23471. Scene.prototype._animate = function () {
  23472. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23473. return;
  23474. }
  23475. // Getting time
  23476. var now = BABYLON.Tools.Now;
  23477. if (!this._animationTimeLast) {
  23478. if (this._pendingData.length > 0) {
  23479. return;
  23480. }
  23481. this._animationTimeLast = now;
  23482. }
  23483. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23484. this._animationTime += deltaTime;
  23485. this._animationTimeLast = now;
  23486. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23487. this._activeAnimatables[index]._animate(this._animationTime);
  23488. }
  23489. // Late animation bindings
  23490. this._processLateAnimationBindings();
  23491. };
  23492. /** @ignore */
  23493. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23494. var target = runtimeAnimation.target;
  23495. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23496. if (!target._lateAnimationHolders) {
  23497. target._lateAnimationHolders = {};
  23498. }
  23499. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23500. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23501. totalWeight: 0,
  23502. animations: []
  23503. };
  23504. }
  23505. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23506. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23507. };
  23508. Scene.prototype._processLateAnimationBindings = function () {
  23509. if (!this._registeredForLateAnimationBindings.length) {
  23510. return;
  23511. }
  23512. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23513. var target = this._registeredForLateAnimationBindings.data[index];
  23514. for (var path in target._lateAnimationHolders) {
  23515. var holder = target._lateAnimationHolders[path];
  23516. // Sanity check
  23517. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23518. continue;
  23519. }
  23520. var normalizer = 1.0;
  23521. var finalValue = void 0;
  23522. if (holder.totalWeight < 1.0) {
  23523. // We need to mix the original value in
  23524. var originalValue = holder.animations[0].originalValue;
  23525. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23526. }
  23527. else {
  23528. // We need to normalize the weights
  23529. normalizer = holder.totalWeight;
  23530. }
  23531. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23532. var runtimeAnimation = holder.animations[animIndex];
  23533. if (finalValue) {
  23534. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23535. }
  23536. else {
  23537. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23538. }
  23539. }
  23540. runtimeAnimation.target[path] = finalValue;
  23541. }
  23542. target._lateAnimationHolders = {};
  23543. }
  23544. this._registeredForLateAnimationBindings.reset();
  23545. };
  23546. // Matrix
  23547. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23548. this._useAlternateCameraConfiguration = active;
  23549. };
  23550. Scene.prototype.getViewMatrix = function () {
  23551. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23552. };
  23553. Scene.prototype.getProjectionMatrix = function () {
  23554. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23555. };
  23556. Scene.prototype.getTransformMatrix = function () {
  23557. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23558. };
  23559. Scene.prototype.setTransformMatrix = function (view, projection) {
  23560. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23561. return;
  23562. }
  23563. this._viewUpdateFlag = view.updateFlag;
  23564. this._projectionUpdateFlag = projection.updateFlag;
  23565. this._viewMatrix = view;
  23566. this._projectionMatrix = projection;
  23567. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23568. // Update frustum
  23569. if (!this._frustumPlanes) {
  23570. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23571. }
  23572. else {
  23573. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23574. }
  23575. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23576. var otherCamera = this.activeCamera._alternateCamera;
  23577. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23578. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23579. }
  23580. if (this._sceneUbo.useUbo) {
  23581. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23582. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23583. this._sceneUbo.update();
  23584. }
  23585. };
  23586. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23587. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23588. return;
  23589. }
  23590. this._alternateViewUpdateFlag = view.updateFlag;
  23591. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23592. this._alternateViewMatrix = view;
  23593. this._alternateProjectionMatrix = projection;
  23594. if (!this._alternateTransformMatrix) {
  23595. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23596. }
  23597. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23598. if (!this._alternateSceneUbo) {
  23599. this._createAlternateUbo();
  23600. }
  23601. if (this._alternateSceneUbo.useUbo) {
  23602. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23603. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23604. this._alternateSceneUbo.update();
  23605. }
  23606. };
  23607. Scene.prototype.getSceneUniformBuffer = function () {
  23608. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23609. };
  23610. // Methods
  23611. Scene.prototype.getUniqueId = function () {
  23612. var result = Scene._uniqueIdCounter;
  23613. Scene._uniqueIdCounter++;
  23614. return result;
  23615. };
  23616. Scene.prototype.addMesh = function (newMesh) {
  23617. this.meshes.push(newMesh);
  23618. //notify the collision coordinator
  23619. if (this.collisionCoordinator) {
  23620. this.collisionCoordinator.onMeshAdded(newMesh);
  23621. }
  23622. newMesh._resyncLightSources();
  23623. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23624. };
  23625. Scene.prototype.removeMesh = function (toRemove) {
  23626. var index = this.meshes.indexOf(toRemove);
  23627. if (index !== -1) {
  23628. // Remove from the scene if mesh found
  23629. this.meshes.splice(index, 1);
  23630. }
  23631. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23632. return index;
  23633. };
  23634. Scene.prototype.addTransformNode = function (newTransformNode) {
  23635. this.transformNodes.push(newTransformNode);
  23636. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23637. };
  23638. Scene.prototype.removeTransformNode = function (toRemove) {
  23639. var index = this.transformNodes.indexOf(toRemove);
  23640. if (index !== -1) {
  23641. // Remove from the scene if found
  23642. this.transformNodes.splice(index, 1);
  23643. }
  23644. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23645. return index;
  23646. };
  23647. Scene.prototype.removeSkeleton = function (toRemove) {
  23648. var index = this.skeletons.indexOf(toRemove);
  23649. if (index !== -1) {
  23650. // Remove from the scene if found
  23651. this.skeletons.splice(index, 1);
  23652. }
  23653. return index;
  23654. };
  23655. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23656. var index = this.morphTargetManagers.indexOf(toRemove);
  23657. if (index !== -1) {
  23658. // Remove from the scene if found
  23659. this.morphTargetManagers.splice(index, 1);
  23660. }
  23661. return index;
  23662. };
  23663. Scene.prototype.removeLight = function (toRemove) {
  23664. var index = this.lights.indexOf(toRemove);
  23665. if (index !== -1) {
  23666. // Remove from meshes
  23667. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23668. var mesh = _a[_i];
  23669. mesh._removeLightSource(toRemove);
  23670. }
  23671. // Remove from the scene if mesh found
  23672. this.lights.splice(index, 1);
  23673. this.sortLightsByPriority();
  23674. }
  23675. this.onLightRemovedObservable.notifyObservers(toRemove);
  23676. return index;
  23677. };
  23678. Scene.prototype.removeCamera = function (toRemove) {
  23679. var index = this.cameras.indexOf(toRemove);
  23680. if (index !== -1) {
  23681. // Remove from the scene if mesh found
  23682. this.cameras.splice(index, 1);
  23683. }
  23684. // Remove from activeCameras
  23685. var index2 = this.activeCameras.indexOf(toRemove);
  23686. if (index2 !== -1) {
  23687. // Remove from the scene if mesh found
  23688. this.activeCameras.splice(index2, 1);
  23689. }
  23690. // Reset the activeCamera
  23691. if (this.activeCamera === toRemove) {
  23692. if (this.cameras.length > 0) {
  23693. this.activeCamera = this.cameras[0];
  23694. }
  23695. else {
  23696. this.activeCamera = null;
  23697. }
  23698. }
  23699. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23700. return index;
  23701. };
  23702. Scene.prototype.removeParticleSystem = function (toRemove) {
  23703. var index = this.particleSystems.indexOf(toRemove);
  23704. if (index !== -1) {
  23705. this.particleSystems.splice(index, 1);
  23706. }
  23707. return index;
  23708. };
  23709. ;
  23710. Scene.prototype.removeAnimation = function (toRemove) {
  23711. var index = this.animations.indexOf(toRemove);
  23712. if (index !== -1) {
  23713. this.animations.splice(index, 1);
  23714. }
  23715. return index;
  23716. };
  23717. ;
  23718. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23719. var index = this.multiMaterials.indexOf(toRemove);
  23720. if (index !== -1) {
  23721. this.multiMaterials.splice(index, 1);
  23722. }
  23723. return index;
  23724. };
  23725. ;
  23726. Scene.prototype.removeMaterial = function (toRemove) {
  23727. var index = this.materials.indexOf(toRemove);
  23728. if (index !== -1) {
  23729. this.materials.splice(index, 1);
  23730. }
  23731. return index;
  23732. };
  23733. ;
  23734. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23735. var index = this.lensFlareSystems.indexOf(toRemove);
  23736. if (index !== -1) {
  23737. this.lensFlareSystems.splice(index, 1);
  23738. }
  23739. return index;
  23740. };
  23741. ;
  23742. Scene.prototype.removeActionManager = function (toRemove) {
  23743. var index = this._actionManagers.indexOf(toRemove);
  23744. if (index !== -1) {
  23745. this._actionManagers.splice(index, 1);
  23746. }
  23747. return index;
  23748. };
  23749. ;
  23750. Scene.prototype.addLight = function (newLight) {
  23751. this.lights.push(newLight);
  23752. this.sortLightsByPriority();
  23753. // Add light to all meshes (To support if the light is removed and then readded)
  23754. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23755. var mesh = _a[_i];
  23756. if (mesh._lightSources.indexOf(newLight) === -1) {
  23757. mesh._lightSources.push(newLight);
  23758. mesh._resyncLightSources();
  23759. }
  23760. }
  23761. this.onNewLightAddedObservable.notifyObservers(newLight);
  23762. };
  23763. Scene.prototype.sortLightsByPriority = function () {
  23764. if (this.requireLightSorting) {
  23765. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23766. }
  23767. };
  23768. Scene.prototype.addCamera = function (newCamera) {
  23769. this.cameras.push(newCamera);
  23770. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23771. };
  23772. Scene.prototype.addSkeleton = function (newSkeleton) {
  23773. this.skeletons.push(newSkeleton);
  23774. };
  23775. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23776. this.particleSystems.push(newParticleSystem);
  23777. };
  23778. Scene.prototype.addAnimation = function (newAnimation) {
  23779. this.animations.push(newAnimation);
  23780. };
  23781. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23782. this.multiMaterials.push(newMultiMaterial);
  23783. };
  23784. Scene.prototype.addMaterial = function (newMaterial) {
  23785. this.materials.push(newMaterial);
  23786. };
  23787. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23788. this.morphTargetManagers.push(newMorphTargetManager);
  23789. };
  23790. Scene.prototype.addGeometry = function (newGeometrie) {
  23791. this._geometries.push(newGeometrie);
  23792. };
  23793. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23794. this.lensFlareSystems.push(newLensFlareSystem);
  23795. };
  23796. Scene.prototype.addActionManager = function (newActionManager) {
  23797. this._actionManagers.push(newActionManager);
  23798. };
  23799. /**
  23800. * Switch active camera
  23801. * @param {Camera} newCamera - new active camera
  23802. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23803. */
  23804. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23805. if (attachControl === void 0) { attachControl = true; }
  23806. var canvas = this._engine.getRenderingCanvas();
  23807. if (!canvas) {
  23808. return;
  23809. }
  23810. if (this.activeCamera) {
  23811. this.activeCamera.detachControl(canvas);
  23812. }
  23813. this.activeCamera = newCamera;
  23814. if (attachControl) {
  23815. newCamera.attachControl(canvas);
  23816. }
  23817. };
  23818. /**
  23819. * sets the active camera of the scene using its ID
  23820. * @param {string} id - the camera's ID
  23821. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23822. * @see activeCamera
  23823. */
  23824. Scene.prototype.setActiveCameraByID = function (id) {
  23825. var camera = this.getCameraByID(id);
  23826. if (camera) {
  23827. this.activeCamera = camera;
  23828. return camera;
  23829. }
  23830. return null;
  23831. };
  23832. /**
  23833. * sets the active camera of the scene using its name
  23834. * @param {string} name - the camera's name
  23835. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23836. * @see activeCamera
  23837. */
  23838. Scene.prototype.setActiveCameraByName = function (name) {
  23839. var camera = this.getCameraByName(name);
  23840. if (camera) {
  23841. this.activeCamera = camera;
  23842. return camera;
  23843. }
  23844. return null;
  23845. };
  23846. /**
  23847. * get an animation group using its name
  23848. * @param {string} the material's name
  23849. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23850. */
  23851. Scene.prototype.getAnimationGroupByName = function (name) {
  23852. for (var index = 0; index < this.animationGroups.length; index++) {
  23853. if (this.animationGroups[index].name === name) {
  23854. return this.animationGroups[index];
  23855. }
  23856. }
  23857. return null;
  23858. };
  23859. /**
  23860. * get a material using its id
  23861. * @param {string} the material's ID
  23862. * @return {BABYLON.Material|null} the material or null if none found.
  23863. */
  23864. Scene.prototype.getMaterialByID = function (id) {
  23865. for (var index = 0; index < this.materials.length; index++) {
  23866. if (this.materials[index].id === id) {
  23867. return this.materials[index];
  23868. }
  23869. }
  23870. return null;
  23871. };
  23872. /**
  23873. * get a material using its name
  23874. * @param {string} the material's name
  23875. * @return {BABYLON.Material|null} the material or null if none found.
  23876. */
  23877. Scene.prototype.getMaterialByName = function (name) {
  23878. for (var index = 0; index < this.materials.length; index++) {
  23879. if (this.materials[index].name === name) {
  23880. return this.materials[index];
  23881. }
  23882. }
  23883. return null;
  23884. };
  23885. Scene.prototype.getLensFlareSystemByName = function (name) {
  23886. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23887. if (this.lensFlareSystems[index].name === name) {
  23888. return this.lensFlareSystems[index];
  23889. }
  23890. }
  23891. return null;
  23892. };
  23893. Scene.prototype.getLensFlareSystemByID = function (id) {
  23894. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23895. if (this.lensFlareSystems[index].id === id) {
  23896. return this.lensFlareSystems[index];
  23897. }
  23898. }
  23899. return null;
  23900. };
  23901. Scene.prototype.getCameraByID = function (id) {
  23902. for (var index = 0; index < this.cameras.length; index++) {
  23903. if (this.cameras[index].id === id) {
  23904. return this.cameras[index];
  23905. }
  23906. }
  23907. return null;
  23908. };
  23909. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23910. for (var index = 0; index < this.cameras.length; index++) {
  23911. if (this.cameras[index].uniqueId === uniqueId) {
  23912. return this.cameras[index];
  23913. }
  23914. }
  23915. return null;
  23916. };
  23917. /**
  23918. * get a camera using its name
  23919. * @param {string} the camera's name
  23920. * @return {BABYLON.Camera|null} the camera or null if none found.
  23921. */
  23922. Scene.prototype.getCameraByName = function (name) {
  23923. for (var index = 0; index < this.cameras.length; index++) {
  23924. if (this.cameras[index].name === name) {
  23925. return this.cameras[index];
  23926. }
  23927. }
  23928. return null;
  23929. };
  23930. /**
  23931. * get a bone using its id
  23932. * @param {string} the bone's id
  23933. * @return {BABYLON.Bone|null} the bone or null if not found
  23934. */
  23935. Scene.prototype.getBoneByID = function (id) {
  23936. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23937. var skeleton = this.skeletons[skeletonIndex];
  23938. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23939. if (skeleton.bones[boneIndex].id === id) {
  23940. return skeleton.bones[boneIndex];
  23941. }
  23942. }
  23943. }
  23944. return null;
  23945. };
  23946. /**
  23947. * get a bone using its id
  23948. * @param {string} the bone's name
  23949. * @return {BABYLON.Bone|null} the bone or null if not found
  23950. */
  23951. Scene.prototype.getBoneByName = function (name) {
  23952. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23953. var skeleton = this.skeletons[skeletonIndex];
  23954. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23955. if (skeleton.bones[boneIndex].name === name) {
  23956. return skeleton.bones[boneIndex];
  23957. }
  23958. }
  23959. }
  23960. return null;
  23961. };
  23962. /**
  23963. * get a light node using its name
  23964. * @param {string} the light's name
  23965. * @return {BABYLON.Light|null} the light or null if none found.
  23966. */
  23967. Scene.prototype.getLightByName = function (name) {
  23968. for (var index = 0; index < this.lights.length; index++) {
  23969. if (this.lights[index].name === name) {
  23970. return this.lights[index];
  23971. }
  23972. }
  23973. return null;
  23974. };
  23975. /**
  23976. * get a light node using its ID
  23977. * @param {string} the light's id
  23978. * @return {BABYLON.Light|null} the light or null if none found.
  23979. */
  23980. Scene.prototype.getLightByID = function (id) {
  23981. for (var index = 0; index < this.lights.length; index++) {
  23982. if (this.lights[index].id === id) {
  23983. return this.lights[index];
  23984. }
  23985. }
  23986. return null;
  23987. };
  23988. /**
  23989. * get a light node using its scene-generated unique ID
  23990. * @param {number} the light's unique id
  23991. * @return {BABYLON.Light|null} the light or null if none found.
  23992. */
  23993. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23994. for (var index = 0; index < this.lights.length; index++) {
  23995. if (this.lights[index].uniqueId === uniqueId) {
  23996. return this.lights[index];
  23997. }
  23998. }
  23999. return null;
  24000. };
  24001. /**
  24002. * get a particle system by id
  24003. * @param id {number} the particle system id
  24004. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  24005. */
  24006. Scene.prototype.getParticleSystemByID = function (id) {
  24007. for (var index = 0; index < this.particleSystems.length; index++) {
  24008. if (this.particleSystems[index].id === id) {
  24009. return this.particleSystems[index];
  24010. }
  24011. }
  24012. return null;
  24013. };
  24014. /**
  24015. * get a geometry using its ID
  24016. * @param {string} the geometry's id
  24017. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  24018. */
  24019. Scene.prototype.getGeometryByID = function (id) {
  24020. for (var index = 0; index < this._geometries.length; index++) {
  24021. if (this._geometries[index].id === id) {
  24022. return this._geometries[index];
  24023. }
  24024. }
  24025. return null;
  24026. };
  24027. /**
  24028. * add a new geometry to this scene.
  24029. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  24030. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  24031. * @return {boolean} was the geometry added or not
  24032. */
  24033. Scene.prototype.pushGeometry = function (geometry, force) {
  24034. if (!force && this.getGeometryByID(geometry.id)) {
  24035. return false;
  24036. }
  24037. this._geometries.push(geometry);
  24038. //notify the collision coordinator
  24039. if (this.collisionCoordinator) {
  24040. this.collisionCoordinator.onGeometryAdded(geometry);
  24041. }
  24042. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24043. return true;
  24044. };
  24045. /**
  24046. * Removes an existing geometry
  24047. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24048. * @return {boolean} was the geometry removed or not
  24049. */
  24050. Scene.prototype.removeGeometry = function (geometry) {
  24051. var index = this._geometries.indexOf(geometry);
  24052. if (index > -1) {
  24053. this._geometries.splice(index, 1);
  24054. //notify the collision coordinator
  24055. if (this.collisionCoordinator) {
  24056. this.collisionCoordinator.onGeometryDeleted(geometry);
  24057. }
  24058. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24059. return true;
  24060. }
  24061. return false;
  24062. };
  24063. Scene.prototype.getGeometries = function () {
  24064. return this._geometries;
  24065. };
  24066. /**
  24067. * Get the first added mesh found of a given ID
  24068. * @param {string} id - the id to search for
  24069. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24070. */
  24071. Scene.prototype.getMeshByID = function (id) {
  24072. for (var index = 0; index < this.meshes.length; index++) {
  24073. if (this.meshes[index].id === id) {
  24074. return this.meshes[index];
  24075. }
  24076. }
  24077. return null;
  24078. };
  24079. Scene.prototype.getMeshesByID = function (id) {
  24080. return this.meshes.filter(function (m) {
  24081. return m.id === id;
  24082. });
  24083. };
  24084. /**
  24085. * Get the first added transform node found of a given ID
  24086. * @param {string} id - the id to search for
  24087. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24088. */
  24089. Scene.prototype.getTransformNodeByID = function (id) {
  24090. for (var index = 0; index < this.transformNodes.length; index++) {
  24091. if (this.transformNodes[index].id === id) {
  24092. return this.transformNodes[index];
  24093. }
  24094. }
  24095. return null;
  24096. };
  24097. Scene.prototype.getTransformNodesByID = function (id) {
  24098. return this.transformNodes.filter(function (m) {
  24099. return m.id === id;
  24100. });
  24101. };
  24102. /**
  24103. * Get a mesh with its auto-generated unique id
  24104. * @param {number} uniqueId - the unique id to search for
  24105. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24106. */
  24107. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24108. for (var index = 0; index < this.meshes.length; index++) {
  24109. if (this.meshes[index].uniqueId === uniqueId) {
  24110. return this.meshes[index];
  24111. }
  24112. }
  24113. return null;
  24114. };
  24115. /**
  24116. * Get a the last added mesh found of a given ID
  24117. * @param {string} id - the id to search for
  24118. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24119. */
  24120. Scene.prototype.getLastMeshByID = function (id) {
  24121. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24122. if (this.meshes[index].id === id) {
  24123. return this.meshes[index];
  24124. }
  24125. }
  24126. return null;
  24127. };
  24128. /**
  24129. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24130. * @param {string} id - the id to search for
  24131. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24132. */
  24133. Scene.prototype.getLastEntryByID = function (id) {
  24134. var index;
  24135. for (index = this.meshes.length - 1; index >= 0; index--) {
  24136. if (this.meshes[index].id === id) {
  24137. return this.meshes[index];
  24138. }
  24139. }
  24140. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24141. if (this.transformNodes[index].id === id) {
  24142. return this.transformNodes[index];
  24143. }
  24144. }
  24145. for (index = this.cameras.length - 1; index >= 0; index--) {
  24146. if (this.cameras[index].id === id) {
  24147. return this.cameras[index];
  24148. }
  24149. }
  24150. for (index = this.lights.length - 1; index >= 0; index--) {
  24151. if (this.lights[index].id === id) {
  24152. return this.lights[index];
  24153. }
  24154. }
  24155. return null;
  24156. };
  24157. Scene.prototype.getNodeByID = function (id) {
  24158. var mesh = this.getMeshByID(id);
  24159. if (mesh) {
  24160. return mesh;
  24161. }
  24162. var light = this.getLightByID(id);
  24163. if (light) {
  24164. return light;
  24165. }
  24166. var camera = this.getCameraByID(id);
  24167. if (camera) {
  24168. return camera;
  24169. }
  24170. var bone = this.getBoneByID(id);
  24171. return bone;
  24172. };
  24173. Scene.prototype.getNodeByName = function (name) {
  24174. var mesh = this.getMeshByName(name);
  24175. if (mesh) {
  24176. return mesh;
  24177. }
  24178. var light = this.getLightByName(name);
  24179. if (light) {
  24180. return light;
  24181. }
  24182. var camera = this.getCameraByName(name);
  24183. if (camera) {
  24184. return camera;
  24185. }
  24186. var bone = this.getBoneByName(name);
  24187. return bone;
  24188. };
  24189. Scene.prototype.getMeshByName = function (name) {
  24190. for (var index = 0; index < this.meshes.length; index++) {
  24191. if (this.meshes[index].name === name) {
  24192. return this.meshes[index];
  24193. }
  24194. }
  24195. return null;
  24196. };
  24197. Scene.prototype.getTransformNodeByName = function (name) {
  24198. for (var index = 0; index < this.transformNodes.length; index++) {
  24199. if (this.transformNodes[index].name === name) {
  24200. return this.transformNodes[index];
  24201. }
  24202. }
  24203. return null;
  24204. };
  24205. Scene.prototype.getSoundByName = function (name) {
  24206. var index;
  24207. if (BABYLON.AudioEngine) {
  24208. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24209. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24210. return this.mainSoundTrack.soundCollection[index];
  24211. }
  24212. }
  24213. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24214. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24215. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24216. return this.soundTracks[sdIndex].soundCollection[index];
  24217. }
  24218. }
  24219. }
  24220. }
  24221. return null;
  24222. };
  24223. Scene.prototype.getLastSkeletonByID = function (id) {
  24224. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24225. if (this.skeletons[index].id === id) {
  24226. return this.skeletons[index];
  24227. }
  24228. }
  24229. return null;
  24230. };
  24231. Scene.prototype.getSkeletonById = function (id) {
  24232. for (var index = 0; index < this.skeletons.length; index++) {
  24233. if (this.skeletons[index].id === id) {
  24234. return this.skeletons[index];
  24235. }
  24236. }
  24237. return null;
  24238. };
  24239. Scene.prototype.getSkeletonByName = function (name) {
  24240. for (var index = 0; index < this.skeletons.length; index++) {
  24241. if (this.skeletons[index].name === name) {
  24242. return this.skeletons[index];
  24243. }
  24244. }
  24245. return null;
  24246. };
  24247. Scene.prototype.getMorphTargetManagerById = function (id) {
  24248. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24249. if (this.morphTargetManagers[index].uniqueId === id) {
  24250. return this.morphTargetManagers[index];
  24251. }
  24252. }
  24253. return null;
  24254. };
  24255. Scene.prototype.isActiveMesh = function (mesh) {
  24256. return (this._activeMeshes.indexOf(mesh) !== -1);
  24257. };
  24258. /**
  24259. * Return a the first highlight layer of the scene with a given name.
  24260. * @param name The name of the highlight layer to look for.
  24261. * @return The highlight layer if found otherwise null.
  24262. */
  24263. Scene.prototype.getHighlightLayerByName = function (name) {
  24264. for (var index = 0; index < this.effectLayers.length; index++) {
  24265. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24266. return this.effectLayers[index];
  24267. }
  24268. }
  24269. return null;
  24270. };
  24271. /**
  24272. * Return a the first highlight layer of the scene with a given name.
  24273. * @param name The name of the highlight layer to look for.
  24274. * @return The highlight layer if found otherwise null.
  24275. */
  24276. Scene.prototype.getGlowLayerByName = function (name) {
  24277. for (var index = 0; index < this.effectLayers.length; index++) {
  24278. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24279. return this.effectLayers[index];
  24280. }
  24281. }
  24282. return null;
  24283. };
  24284. Object.defineProperty(Scene.prototype, "uid", {
  24285. /**
  24286. * Return a unique id as a string which can serve as an identifier for the scene
  24287. */
  24288. get: function () {
  24289. if (!this._uid) {
  24290. this._uid = BABYLON.Tools.RandomId();
  24291. }
  24292. return this._uid;
  24293. },
  24294. enumerable: true,
  24295. configurable: true
  24296. });
  24297. /**
  24298. * Add an externaly attached data from its key.
  24299. * This method call will fail and return false, if such key already exists.
  24300. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24301. * @param key the unique key that identifies the data
  24302. * @param data the data object to associate to the key for this Engine instance
  24303. * @return true if no such key were already present and the data was added successfully, false otherwise
  24304. */
  24305. Scene.prototype.addExternalData = function (key, data) {
  24306. if (!this._externalData) {
  24307. this._externalData = new BABYLON.StringDictionary();
  24308. }
  24309. return this._externalData.add(key, data);
  24310. };
  24311. /**
  24312. * Get an externaly attached data from its key
  24313. * @param key the unique key that identifies the data
  24314. * @return the associated data, if present (can be null), or undefined if not present
  24315. */
  24316. Scene.prototype.getExternalData = function (key) {
  24317. if (!this._externalData) {
  24318. return null;
  24319. }
  24320. return this._externalData.get(key);
  24321. };
  24322. /**
  24323. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24324. * @param key the unique key that identifies the data
  24325. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24326. * @return the associated data, can be null if the factory returned null.
  24327. */
  24328. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24329. if (!this._externalData) {
  24330. this._externalData = new BABYLON.StringDictionary();
  24331. }
  24332. return this._externalData.getOrAddWithFactory(key, factory);
  24333. };
  24334. /**
  24335. * Remove an externaly attached data from the Engine instance
  24336. * @param key the unique key that identifies the data
  24337. * @return true if the data was successfully removed, false if it doesn't exist
  24338. */
  24339. Scene.prototype.removeExternalData = function (key) {
  24340. return this._externalData.remove(key);
  24341. };
  24342. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24343. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24344. if (mesh.showSubMeshesBoundingBox) {
  24345. var boundingInfo = subMesh.getBoundingInfo();
  24346. if (boundingInfo !== null && boundingInfo !== undefined) {
  24347. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24348. }
  24349. }
  24350. var material = subMesh.getMaterial();
  24351. if (material !== null && material !== undefined) {
  24352. // Render targets
  24353. if (material.getRenderTargetTextures !== undefined) {
  24354. if (this._processedMaterials.indexOf(material) === -1) {
  24355. this._processedMaterials.push(material);
  24356. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24357. }
  24358. }
  24359. // Dispatch
  24360. this._activeIndices.addCount(subMesh.indexCount, false);
  24361. this._renderingManager.dispatch(subMesh, mesh, material);
  24362. }
  24363. }
  24364. };
  24365. /**
  24366. * Clear the processed materials smart array preventing retention point in material dispose.
  24367. */
  24368. Scene.prototype.freeProcessedMaterials = function () {
  24369. this._processedMaterials.dispose();
  24370. };
  24371. /**
  24372. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24373. */
  24374. Scene.prototype.freeActiveMeshes = function () {
  24375. this._activeMeshes.dispose();
  24376. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24377. this.activeCamera._activeMeshes.dispose();
  24378. }
  24379. if (this.activeCameras) {
  24380. for (var i = 0; i < this.activeCameras.length; i++) {
  24381. var activeCamera = this.activeCameras[i];
  24382. if (activeCamera && activeCamera._activeMeshes) {
  24383. activeCamera._activeMeshes.dispose();
  24384. }
  24385. }
  24386. }
  24387. };
  24388. /**
  24389. * Clear the info related to rendering groups preventing retention points during dispose.
  24390. */
  24391. Scene.prototype.freeRenderingGroups = function () {
  24392. if (this._renderingManager) {
  24393. this._renderingManager.freeRenderingGroups();
  24394. }
  24395. if (this.textures) {
  24396. for (var i = 0; i < this.textures.length; i++) {
  24397. var texture = this.textures[i];
  24398. if (texture && texture.renderList) {
  24399. texture.freeRenderingGroups();
  24400. }
  24401. }
  24402. }
  24403. };
  24404. Scene.prototype._isInIntermediateRendering = function () {
  24405. return this._intermediateRendering;
  24406. };
  24407. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24408. this._activeMeshCandidateProvider = provider;
  24409. };
  24410. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24411. return this._activeMeshCandidateProvider;
  24412. };
  24413. /**
  24414. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24415. */
  24416. Scene.prototype.freezeActiveMeshes = function () {
  24417. if (!this.activeCamera) {
  24418. return this;
  24419. }
  24420. if (!this._frustumPlanes) {
  24421. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24422. }
  24423. this._evaluateActiveMeshes();
  24424. this._activeMeshesFrozen = true;
  24425. return this;
  24426. };
  24427. /**
  24428. * Use this function to restart evaluating active meshes on every frame
  24429. */
  24430. Scene.prototype.unfreezeActiveMeshes = function () {
  24431. this._activeMeshesFrozen = false;
  24432. return this;
  24433. };
  24434. Scene.prototype._evaluateActiveMeshes = function () {
  24435. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24436. return;
  24437. }
  24438. if (!this.activeCamera) {
  24439. return;
  24440. }
  24441. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24442. this.activeCamera._activeMeshes.reset();
  24443. this._activeMeshes.reset();
  24444. this._renderingManager.reset();
  24445. this._processedMaterials.reset();
  24446. this._activeParticleSystems.reset();
  24447. this._activeSkeletons.reset();
  24448. this._softwareSkinnedMeshes.reset();
  24449. if (this._boundingBoxRenderer) {
  24450. this._boundingBoxRenderer.reset();
  24451. }
  24452. // Meshes
  24453. var meshes;
  24454. var len;
  24455. var checkIsEnabled = true;
  24456. // Determine mesh candidates
  24457. if (this._activeMeshCandidateProvider !== undefined) {
  24458. // Use _activeMeshCandidateProvider
  24459. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24460. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24461. if (meshes !== undefined) {
  24462. len = meshes.length;
  24463. }
  24464. else {
  24465. len = 0;
  24466. }
  24467. }
  24468. else if (this._selectionOctree !== undefined) {
  24469. // Octree
  24470. var selection = this._selectionOctree.select(this._frustumPlanes);
  24471. meshes = selection.data;
  24472. len = selection.length;
  24473. }
  24474. else {
  24475. // Full scene traversal
  24476. len = this.meshes.length;
  24477. meshes = this.meshes;
  24478. }
  24479. // Check each mesh
  24480. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24481. mesh = meshes[meshIndex];
  24482. if (mesh.isBlocked) {
  24483. continue;
  24484. }
  24485. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24486. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24487. continue;
  24488. }
  24489. mesh.computeWorldMatrix();
  24490. // Intersections
  24491. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24492. this._meshesForIntersections.pushNoDuplicate(mesh);
  24493. }
  24494. // Switch to current LOD
  24495. meshLOD = mesh.getLOD(this.activeCamera);
  24496. if (meshLOD === undefined || meshLOD === null) {
  24497. continue;
  24498. }
  24499. mesh._preActivate();
  24500. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24501. this._activeMeshes.push(mesh);
  24502. this.activeCamera._activeMeshes.push(mesh);
  24503. mesh._activate(this._renderId);
  24504. if (meshLOD !== mesh) {
  24505. meshLOD._activate(this._renderId);
  24506. }
  24507. this._activeMesh(mesh, meshLOD);
  24508. }
  24509. }
  24510. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24511. // Particle systems
  24512. if (this.particlesEnabled) {
  24513. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24514. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24515. var particleSystem = this.particleSystems[particleIndex];
  24516. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24517. continue;
  24518. }
  24519. var emitter = particleSystem.emitter;
  24520. if (!emitter.position || emitter.isEnabled()) {
  24521. this._activeParticleSystems.push(particleSystem);
  24522. particleSystem.animate();
  24523. this._renderingManager.dispatchParticles(particleSystem);
  24524. }
  24525. }
  24526. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24527. }
  24528. };
  24529. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24530. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24531. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24532. mesh.skeleton.prepare();
  24533. }
  24534. if (!mesh.computeBonesUsingShaders) {
  24535. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24536. }
  24537. }
  24538. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24539. var boundingInfo = sourceMesh.getBoundingInfo();
  24540. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24541. }
  24542. if (mesh !== undefined && mesh !== null
  24543. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24544. // Submeshes Octrees
  24545. var len;
  24546. var subMeshes;
  24547. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24548. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24549. len = intersections.length;
  24550. subMeshes = intersections.data;
  24551. }
  24552. else {
  24553. subMeshes = mesh.subMeshes;
  24554. len = subMeshes.length;
  24555. }
  24556. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24557. subMesh = subMeshes[subIndex];
  24558. this._evaluateSubMesh(subMesh, mesh);
  24559. }
  24560. }
  24561. };
  24562. Scene.prototype.updateTransformMatrix = function (force) {
  24563. if (!this.activeCamera) {
  24564. return;
  24565. }
  24566. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24567. };
  24568. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24569. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24570. };
  24571. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24572. if (camera && camera._skipRendering) {
  24573. return;
  24574. }
  24575. var engine = this._engine;
  24576. this.activeCamera = camera;
  24577. if (!this.activeCamera)
  24578. throw new Error("Active camera not set");
  24579. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24580. // Viewport
  24581. engine.setViewport(this.activeCamera.viewport);
  24582. // Camera
  24583. this.resetCachedMaterial();
  24584. this._renderId++;
  24585. this.updateTransformMatrix();
  24586. if (camera._alternateCamera) {
  24587. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24588. this._alternateRendering = true;
  24589. }
  24590. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24591. // Meshes
  24592. this._evaluateActiveMeshes();
  24593. // Software skinning
  24594. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24595. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24596. mesh.applySkeleton(mesh.skeleton);
  24597. }
  24598. // Render targets
  24599. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24600. var needsRestoreFrameBuffer = false;
  24601. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24602. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24603. }
  24604. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24605. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24606. }
  24607. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24608. this._intermediateRendering = true;
  24609. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24610. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24611. var renderTarget = this._renderTargets.data[renderIndex];
  24612. if (renderTarget._shouldRender()) {
  24613. this._renderId++;
  24614. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24615. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24616. }
  24617. }
  24618. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24619. this._intermediateRendering = false;
  24620. this._renderId++;
  24621. needsRestoreFrameBuffer = true; // Restore back buffer
  24622. }
  24623. // Render EffecttLayer Texture
  24624. var stencilState = this._engine.getStencilBuffer();
  24625. var renderEffects = false;
  24626. var needStencil = false;
  24627. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24628. this._intermediateRendering = true;
  24629. for (var i = 0; i < this.effectLayers.length; i++) {
  24630. var effectLayer = this.effectLayers[i];
  24631. if (effectLayer.shouldRender() &&
  24632. (!effectLayer.camera ||
  24633. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24634. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24635. renderEffects = true;
  24636. needStencil = needStencil || effectLayer.needStencil();
  24637. var renderTarget = effectLayer._mainTexture;
  24638. if (renderTarget._shouldRender()) {
  24639. this._renderId++;
  24640. renderTarget.render(false, false);
  24641. needsRestoreFrameBuffer = true;
  24642. }
  24643. }
  24644. }
  24645. this._intermediateRendering = false;
  24646. this._renderId++;
  24647. }
  24648. if (needsRestoreFrameBuffer) {
  24649. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24650. }
  24651. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24652. // Prepare Frame
  24653. this.postProcessManager._prepareFrame();
  24654. // Backgrounds
  24655. var layerIndex;
  24656. var layer;
  24657. if (this.layers.length) {
  24658. engine.setDepthBuffer(false);
  24659. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24660. layer = this.layers[layerIndex];
  24661. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24662. layer.render();
  24663. }
  24664. }
  24665. engine.setDepthBuffer(true);
  24666. }
  24667. // Activate effect Layer stencil
  24668. if (needStencil) {
  24669. this._engine.setStencilBuffer(true);
  24670. }
  24671. // Render
  24672. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24673. this._renderingManager.render(null, null, true, true);
  24674. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24675. // Restore effect Layer stencil
  24676. if (needStencil) {
  24677. this._engine.setStencilBuffer(stencilState);
  24678. }
  24679. // Bounding boxes
  24680. if (this._boundingBoxRenderer) {
  24681. this._boundingBoxRenderer.render();
  24682. }
  24683. // Lens flares
  24684. if (this.lensFlaresEnabled) {
  24685. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24686. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24687. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24688. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24689. lensFlareSystem.render();
  24690. }
  24691. }
  24692. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24693. }
  24694. // Foregrounds
  24695. if (this.layers.length) {
  24696. engine.setDepthBuffer(false);
  24697. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24698. layer = this.layers[layerIndex];
  24699. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24700. layer.render();
  24701. }
  24702. }
  24703. engine.setDepthBuffer(true);
  24704. }
  24705. // Effect Layer
  24706. if (renderEffects) {
  24707. engine.setDepthBuffer(false);
  24708. for (var i = 0; i < this.effectLayers.length; i++) {
  24709. if (this.effectLayers[i].shouldRender()) {
  24710. this.effectLayers[i].render();
  24711. }
  24712. }
  24713. engine.setDepthBuffer(true);
  24714. }
  24715. // Finalize frame
  24716. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24717. // Reset some special arrays
  24718. this._renderTargets.reset();
  24719. this._alternateRendering = false;
  24720. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24721. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24722. };
  24723. Scene.prototype._processSubCameras = function (camera) {
  24724. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24725. this._renderForCamera(camera);
  24726. return;
  24727. }
  24728. // rig cameras
  24729. for (var index = 0; index < camera._rigCameras.length; index++) {
  24730. this._renderForCamera(camera._rigCameras[index], camera);
  24731. }
  24732. this.activeCamera = camera;
  24733. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24734. };
  24735. Scene.prototype._checkIntersections = function () {
  24736. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24737. var sourceMesh = this._meshesForIntersections.data[index];
  24738. if (!sourceMesh.actionManager) {
  24739. continue;
  24740. }
  24741. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24742. var action = sourceMesh.actionManager.actions[actionIndex];
  24743. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24744. var parameters = action.getTriggerParameter();
  24745. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24746. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24747. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24748. if (areIntersecting && currentIntersectionInProgress === -1) {
  24749. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24750. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24751. sourceMesh._intersectionsInProgress.push(otherMesh);
  24752. }
  24753. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24754. sourceMesh._intersectionsInProgress.push(otherMesh);
  24755. }
  24756. }
  24757. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24758. //They intersected, and now they don't.
  24759. //is this trigger an exit trigger? execute an event.
  24760. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24761. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24762. }
  24763. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24764. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24765. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24766. }
  24767. }
  24768. }
  24769. }
  24770. }
  24771. };
  24772. Scene.prototype.render = function () {
  24773. if (this.isDisposed) {
  24774. return;
  24775. }
  24776. this._activeParticles.fetchNewFrame();
  24777. this._totalVertices.fetchNewFrame();
  24778. this._activeIndices.fetchNewFrame();
  24779. this._activeBones.fetchNewFrame();
  24780. this._meshesForIntersections.reset();
  24781. this.resetCachedMaterial();
  24782. this.onBeforeAnimationsObservable.notifyObservers(this);
  24783. // Actions
  24784. if (this.actionManager) {
  24785. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24786. }
  24787. //Simplification Queue
  24788. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24789. this.simplificationQueue.executeNext();
  24790. }
  24791. if (this._engine.isDeterministicLockStep()) {
  24792. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24793. var defaultFPS = (60.0 / 1000.0);
  24794. var defaultFrameTime = 1000 / 60; // frame time in MS
  24795. if (this._physicsEngine) {
  24796. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24797. }
  24798. var stepsTaken = 0;
  24799. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24800. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24801. internalSteps = Math.min(internalSteps, maxSubSteps);
  24802. do {
  24803. this.onBeforeStepObservable.notifyObservers(this);
  24804. // Animations
  24805. this._animationRatio = defaultFrameTime * defaultFPS;
  24806. this._animate();
  24807. this.onAfterAnimationsObservable.notifyObservers(this);
  24808. // Physics
  24809. if (this._physicsEngine) {
  24810. this.onBeforePhysicsObservable.notifyObservers(this);
  24811. this._physicsEngine._step(defaultFrameTime / 1000);
  24812. this.onAfterPhysicsObservable.notifyObservers(this);
  24813. }
  24814. this.onAfterStepObservable.notifyObservers(this);
  24815. this._currentStepId++;
  24816. stepsTaken++;
  24817. deltaTime -= defaultFrameTime;
  24818. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24819. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24820. }
  24821. else {
  24822. // Animations
  24823. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24824. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24825. this._animate();
  24826. this.onAfterAnimationsObservable.notifyObservers(this);
  24827. // Physics
  24828. if (this._physicsEngine) {
  24829. this.onBeforePhysicsObservable.notifyObservers(this);
  24830. this._physicsEngine._step(deltaTime / 1000.0);
  24831. this.onAfterPhysicsObservable.notifyObservers(this);
  24832. }
  24833. }
  24834. // update gamepad manager
  24835. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24836. this._gamepadManager._checkGamepadsStatus();
  24837. }
  24838. // Update Cameras
  24839. if (this.activeCameras.length > 0) {
  24840. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24841. var camera = this.activeCameras[cameraIndex];
  24842. camera.update();
  24843. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24844. // rig cameras
  24845. for (var index = 0; index < camera._rigCameras.length; index++) {
  24846. camera._rigCameras[index].update();
  24847. }
  24848. }
  24849. }
  24850. }
  24851. else if (this.activeCamera) {
  24852. this.activeCamera.update();
  24853. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24854. // rig cameras
  24855. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24856. this.activeCamera._rigCameras[index].update();
  24857. }
  24858. }
  24859. }
  24860. // Before render
  24861. this.onBeforeRenderObservable.notifyObservers(this);
  24862. // Customs render targets
  24863. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24864. var engine = this.getEngine();
  24865. var currentActiveCamera = this.activeCamera;
  24866. if (this.renderTargetsEnabled) {
  24867. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24868. this._intermediateRendering = true;
  24869. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24870. var renderTarget = this.customRenderTargets[customIndex];
  24871. if (renderTarget._shouldRender()) {
  24872. this._renderId++;
  24873. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24874. if (!this.activeCamera)
  24875. throw new Error("Active camera not set");
  24876. // Viewport
  24877. engine.setViewport(this.activeCamera.viewport);
  24878. // Camera
  24879. this.updateTransformMatrix();
  24880. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24881. }
  24882. }
  24883. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24884. this._intermediateRendering = false;
  24885. this._renderId++;
  24886. }
  24887. // Restore back buffer
  24888. if (this.customRenderTargets.length > 0) {
  24889. engine.restoreDefaultFramebuffer();
  24890. }
  24891. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24892. this.activeCamera = currentActiveCamera;
  24893. // Procedural textures
  24894. if (this.proceduralTexturesEnabled) {
  24895. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24896. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24897. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24898. if (proceduralTexture._shouldRender()) {
  24899. proceduralTexture.render();
  24900. }
  24901. }
  24902. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24903. }
  24904. // Clear
  24905. if (this.autoClearDepthAndStencil || this.autoClear) {
  24906. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24907. }
  24908. // Shadows
  24909. if (this.shadowsEnabled) {
  24910. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24911. var light = this.lights[lightIndex];
  24912. var shadowGenerator = light.getShadowGenerator();
  24913. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24914. var shadowMap = (shadowGenerator.getShadowMap());
  24915. if (this.textures.indexOf(shadowMap) !== -1) {
  24916. this._renderTargets.push(shadowMap);
  24917. }
  24918. }
  24919. }
  24920. }
  24921. // Depth renderer
  24922. for (var key in this._depthRenderer) {
  24923. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24924. }
  24925. // Geometry renderer
  24926. if (this._geometryBufferRenderer) {
  24927. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24928. }
  24929. // RenderPipeline
  24930. if (this._postProcessRenderPipelineManager) {
  24931. this._postProcessRenderPipelineManager.update();
  24932. }
  24933. // Multi-cameras?
  24934. if (this.activeCameras.length > 0) {
  24935. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24936. if (cameraIndex > 0) {
  24937. this._engine.clear(null, false, true, true);
  24938. }
  24939. this._processSubCameras(this.activeCameras[cameraIndex]);
  24940. }
  24941. }
  24942. else {
  24943. if (!this.activeCamera) {
  24944. throw new Error("No camera defined");
  24945. }
  24946. this._processSubCameras(this.activeCamera);
  24947. }
  24948. // Intersection checks
  24949. this._checkIntersections();
  24950. // Update the audio listener attached to the camera
  24951. if (BABYLON.AudioEngine) {
  24952. this._updateAudioParameters();
  24953. }
  24954. // After render
  24955. if (this.afterRender) {
  24956. this.afterRender();
  24957. }
  24958. this.onAfterRenderObservable.notifyObservers(this);
  24959. // Cleaning
  24960. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24961. var data = this._toBeDisposed.data[index];
  24962. if (data) {
  24963. data.dispose();
  24964. }
  24965. this._toBeDisposed[index] = null;
  24966. }
  24967. this._toBeDisposed.reset();
  24968. if (this.dumpNextRenderTargets) {
  24969. this.dumpNextRenderTargets = false;
  24970. }
  24971. this._activeBones.addCount(0, true);
  24972. this._activeIndices.addCount(0, true);
  24973. this._activeParticles.addCount(0, true);
  24974. };
  24975. Scene.prototype._updateAudioParameters = function () {
  24976. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24977. return;
  24978. }
  24979. var listeningCamera;
  24980. var audioEngine = BABYLON.Engine.audioEngine;
  24981. if (this.activeCameras.length > 0) {
  24982. listeningCamera = this.activeCameras[0];
  24983. }
  24984. else {
  24985. listeningCamera = this.activeCamera;
  24986. }
  24987. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24988. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24989. // for VR cameras
  24990. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24991. listeningCamera = listeningCamera.rigCameras[0];
  24992. }
  24993. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24994. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24995. cameraDirection.normalize();
  24996. // To avoid some errors on GearVR
  24997. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24998. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24999. }
  25000. var i;
  25001. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25002. var sound = this.mainSoundTrack.soundCollection[i];
  25003. if (sound.useCustomAttenuation) {
  25004. sound.updateDistanceFromListener();
  25005. }
  25006. }
  25007. for (i = 0; i < this.soundTracks.length; i++) {
  25008. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25009. sound = this.soundTracks[i].soundCollection[j];
  25010. if (sound.useCustomAttenuation) {
  25011. sound.updateDistanceFromListener();
  25012. }
  25013. }
  25014. }
  25015. }
  25016. };
  25017. Object.defineProperty(Scene.prototype, "audioEnabled", {
  25018. // Audio
  25019. get: function () {
  25020. return this._audioEnabled;
  25021. },
  25022. set: function (value) {
  25023. this._audioEnabled = value;
  25024. if (BABYLON.AudioEngine) {
  25025. if (this._audioEnabled) {
  25026. this._enableAudio();
  25027. }
  25028. else {
  25029. this._disableAudio();
  25030. }
  25031. }
  25032. },
  25033. enumerable: true,
  25034. configurable: true
  25035. });
  25036. Scene.prototype._disableAudio = function () {
  25037. var i;
  25038. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25039. this.mainSoundTrack.soundCollection[i].pause();
  25040. }
  25041. for (i = 0; i < this.soundTracks.length; i++) {
  25042. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25043. this.soundTracks[i].soundCollection[j].pause();
  25044. }
  25045. }
  25046. };
  25047. Scene.prototype._enableAudio = function () {
  25048. var i;
  25049. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25050. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25051. this.mainSoundTrack.soundCollection[i].play();
  25052. }
  25053. }
  25054. for (i = 0; i < this.soundTracks.length; i++) {
  25055. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25056. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25057. this.soundTracks[i].soundCollection[j].play();
  25058. }
  25059. }
  25060. }
  25061. };
  25062. Object.defineProperty(Scene.prototype, "headphone", {
  25063. get: function () {
  25064. return this._headphone;
  25065. },
  25066. set: function (value) {
  25067. this._headphone = value;
  25068. if (BABYLON.AudioEngine) {
  25069. if (this._headphone) {
  25070. this._switchAudioModeForHeadphones();
  25071. }
  25072. else {
  25073. this._switchAudioModeForNormalSpeakers();
  25074. }
  25075. }
  25076. },
  25077. enumerable: true,
  25078. configurable: true
  25079. });
  25080. Scene.prototype._switchAudioModeForHeadphones = function () {
  25081. this.mainSoundTrack.switchPanningModelToHRTF();
  25082. for (var i = 0; i < this.soundTracks.length; i++) {
  25083. this.soundTracks[i].switchPanningModelToHRTF();
  25084. }
  25085. };
  25086. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25087. this.mainSoundTrack.switchPanningModelToEqualPower();
  25088. for (var i = 0; i < this.soundTracks.length; i++) {
  25089. this.soundTracks[i].switchPanningModelToEqualPower();
  25090. }
  25091. };
  25092. /**
  25093. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25094. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25095. * @returns the created depth renderer
  25096. */
  25097. Scene.prototype.enableDepthRenderer = function (camera) {
  25098. camera = camera || this.activeCamera;
  25099. if (!camera) {
  25100. throw "No camera available to enable depth renderer";
  25101. }
  25102. if (!this._depthRenderer[camera.id]) {
  25103. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25104. }
  25105. return this._depthRenderer[camera.id];
  25106. };
  25107. /**
  25108. * Disables a depth renderer for a given camera
  25109. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25110. */
  25111. Scene.prototype.disableDepthRenderer = function (camera) {
  25112. camera = camera || this.activeCamera;
  25113. if (!camera || !this._depthRenderer[camera.id]) {
  25114. return;
  25115. }
  25116. this._depthRenderer[camera.id].dispose();
  25117. delete this._depthRenderer[camera.id];
  25118. };
  25119. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25120. if (ratio === void 0) { ratio = 1; }
  25121. if (this._geometryBufferRenderer) {
  25122. return this._geometryBufferRenderer;
  25123. }
  25124. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25125. if (!this._geometryBufferRenderer.isSupported) {
  25126. this._geometryBufferRenderer = null;
  25127. }
  25128. return this._geometryBufferRenderer;
  25129. };
  25130. Scene.prototype.disableGeometryBufferRenderer = function () {
  25131. if (!this._geometryBufferRenderer) {
  25132. return;
  25133. }
  25134. this._geometryBufferRenderer.dispose();
  25135. this._geometryBufferRenderer = null;
  25136. };
  25137. Scene.prototype.freezeMaterials = function () {
  25138. for (var i = 0; i < this.materials.length; i++) {
  25139. this.materials[i].freeze();
  25140. }
  25141. };
  25142. Scene.prototype.unfreezeMaterials = function () {
  25143. for (var i = 0; i < this.materials.length; i++) {
  25144. this.materials[i].unfreeze();
  25145. }
  25146. };
  25147. Scene.prototype.dispose = function () {
  25148. this.beforeRender = null;
  25149. this.afterRender = null;
  25150. this.skeletons = [];
  25151. this.morphTargetManagers = [];
  25152. this.importedMeshesFiles = new Array();
  25153. this.stopAllAnimations();
  25154. this.resetCachedMaterial();
  25155. for (var key in this._depthRenderer) {
  25156. this._depthRenderer[key].dispose();
  25157. }
  25158. if (this._gamepadManager) {
  25159. this._gamepadManager.dispose();
  25160. this._gamepadManager = null;
  25161. }
  25162. // Smart arrays
  25163. if (this.activeCamera) {
  25164. this.activeCamera._activeMeshes.dispose();
  25165. this.activeCamera = null;
  25166. }
  25167. this._activeMeshes.dispose();
  25168. this._renderingManager.dispose();
  25169. this._processedMaterials.dispose();
  25170. this._activeParticleSystems.dispose();
  25171. this._activeSkeletons.dispose();
  25172. this._softwareSkinnedMeshes.dispose();
  25173. this._renderTargets.dispose();
  25174. this._registeredForLateAnimationBindings.dispose();
  25175. if (this._boundingBoxRenderer) {
  25176. this._boundingBoxRenderer.dispose();
  25177. }
  25178. this._meshesForIntersections.dispose();
  25179. this._toBeDisposed.dispose();
  25180. // Abort active requests
  25181. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25182. var request = _a[_i];
  25183. request.abort();
  25184. }
  25185. // Debug layer
  25186. if (this._debugLayer) {
  25187. this._debugLayer.hide();
  25188. }
  25189. // Events
  25190. this.onDisposeObservable.notifyObservers(this);
  25191. this.onDisposeObservable.clear();
  25192. this.onBeforeRenderObservable.clear();
  25193. this.onAfterRenderObservable.clear();
  25194. this.OnBeforeRenderTargetsRenderObservable.clear();
  25195. this.OnAfterRenderTargetsRenderObservable.clear();
  25196. this.onAfterStepObservable.clear();
  25197. this.onBeforeStepObservable.clear();
  25198. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25199. this.onAfterActiveMeshesEvaluationObservable.clear();
  25200. this.onBeforeParticlesRenderingObservable.clear();
  25201. this.onAfterParticlesRenderingObservable.clear();
  25202. this.onBeforeSpritesRenderingObservable.clear();
  25203. this.onAfterSpritesRenderingObservable.clear();
  25204. this.onBeforeDrawPhaseObservable.clear();
  25205. this.onAfterDrawPhaseObservable.clear();
  25206. this.onBeforePhysicsObservable.clear();
  25207. this.onAfterPhysicsObservable.clear();
  25208. this.onBeforeAnimationsObservable.clear();
  25209. this.onAfterAnimationsObservable.clear();
  25210. this.onDataLoadedObservable.clear();
  25211. this.detachControl();
  25212. // Release sounds & sounds tracks
  25213. if (BABYLON.AudioEngine) {
  25214. this.disposeSounds();
  25215. }
  25216. // VR Helper
  25217. if (this.VRHelper) {
  25218. this.VRHelper.dispose();
  25219. }
  25220. // Detach cameras
  25221. var canvas = this._engine.getRenderingCanvas();
  25222. if (canvas) {
  25223. var index;
  25224. for (index = 0; index < this.cameras.length; index++) {
  25225. this.cameras[index].detachControl(canvas);
  25226. }
  25227. }
  25228. // Release animation groups
  25229. while (this.animationGroups.length) {
  25230. this.animationGroups[0].dispose();
  25231. }
  25232. // Release lights
  25233. while (this.lights.length) {
  25234. this.lights[0].dispose();
  25235. }
  25236. // Release meshes
  25237. while (this.meshes.length) {
  25238. this.meshes[0].dispose(true);
  25239. }
  25240. while (this.transformNodes.length) {
  25241. this.removeTransformNode(this.transformNodes[0]);
  25242. }
  25243. // Release cameras
  25244. while (this.cameras.length) {
  25245. this.cameras[0].dispose();
  25246. }
  25247. // Release materials
  25248. if (this.defaultMaterial) {
  25249. this.defaultMaterial.dispose();
  25250. }
  25251. while (this.multiMaterials.length) {
  25252. this.multiMaterials[0].dispose();
  25253. }
  25254. while (this.materials.length) {
  25255. this.materials[0].dispose();
  25256. }
  25257. // Release particles
  25258. while (this.particleSystems.length) {
  25259. this.particleSystems[0].dispose();
  25260. }
  25261. // Release sprites
  25262. while (this.spriteManagers.length) {
  25263. this.spriteManagers[0].dispose();
  25264. }
  25265. // Release postProcesses
  25266. while (this.postProcesses.length) {
  25267. this.postProcesses[0].dispose();
  25268. }
  25269. // Release layers
  25270. while (this.layers.length) {
  25271. this.layers[0].dispose();
  25272. }
  25273. while (this.effectLayers.length) {
  25274. this.effectLayers[0].dispose();
  25275. }
  25276. // Release textures
  25277. while (this.textures.length) {
  25278. this.textures[0].dispose();
  25279. }
  25280. // Release UBO
  25281. this._sceneUbo.dispose();
  25282. if (this._alternateSceneUbo) {
  25283. this._alternateSceneUbo.dispose();
  25284. }
  25285. // Post-processes
  25286. this.postProcessManager.dispose();
  25287. if (this._postProcessRenderPipelineManager) {
  25288. this._postProcessRenderPipelineManager.dispose();
  25289. }
  25290. // Physics
  25291. if (this._physicsEngine) {
  25292. this.disablePhysicsEngine();
  25293. }
  25294. // Remove from engine
  25295. index = this._engine.scenes.indexOf(this);
  25296. if (index > -1) {
  25297. this._engine.scenes.splice(index, 1);
  25298. }
  25299. this._engine.wipeCaches(true);
  25300. this._isDisposed = true;
  25301. };
  25302. Object.defineProperty(Scene.prototype, "isDisposed", {
  25303. get: function () {
  25304. return this._isDisposed;
  25305. },
  25306. enumerable: true,
  25307. configurable: true
  25308. });
  25309. // Release sounds & sounds tracks
  25310. Scene.prototype.disposeSounds = function () {
  25311. if (!this._mainSoundTrack) {
  25312. return;
  25313. }
  25314. this.mainSoundTrack.dispose();
  25315. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25316. this.soundTracks[scIndex].dispose();
  25317. }
  25318. };
  25319. // Octrees
  25320. /**
  25321. * Get the world extend vectors with an optional filter
  25322. *
  25323. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25324. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25325. */
  25326. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25327. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25328. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25329. filterPredicate = filterPredicate || (function () { return true; });
  25330. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25331. mesh.computeWorldMatrix(true);
  25332. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25333. return;
  25334. }
  25335. var boundingInfo = mesh.getBoundingInfo();
  25336. var minBox = boundingInfo.boundingBox.minimumWorld;
  25337. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25338. BABYLON.Tools.CheckExtends(minBox, min, max);
  25339. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25340. });
  25341. return {
  25342. min: min,
  25343. max: max
  25344. };
  25345. };
  25346. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25347. if (maxCapacity === void 0) { maxCapacity = 64; }
  25348. if (maxDepth === void 0) { maxDepth = 2; }
  25349. if (!this._selectionOctree) {
  25350. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25351. }
  25352. var worldExtends = this.getWorldExtends();
  25353. // Update octree
  25354. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25355. return this._selectionOctree;
  25356. };
  25357. // Picking
  25358. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25359. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25360. var result = BABYLON.Ray.Zero();
  25361. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25362. return result;
  25363. };
  25364. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25365. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25366. var engine = this._engine;
  25367. if (!camera) {
  25368. if (!this.activeCamera)
  25369. throw new Error("Active camera not set");
  25370. camera = this.activeCamera;
  25371. }
  25372. var cameraViewport = camera.viewport;
  25373. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25374. // Moving coordinates to local viewport world
  25375. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25376. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25377. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25378. return this;
  25379. };
  25380. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25381. var result = BABYLON.Ray.Zero();
  25382. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25383. return result;
  25384. };
  25385. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25386. if (!BABYLON.PickingInfo) {
  25387. return this;
  25388. }
  25389. var engine = this._engine;
  25390. if (!camera) {
  25391. if (!this.activeCamera)
  25392. throw new Error("Active camera not set");
  25393. camera = this.activeCamera;
  25394. }
  25395. var cameraViewport = camera.viewport;
  25396. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25397. var identity = BABYLON.Matrix.Identity();
  25398. // Moving coordinates to local viewport world
  25399. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25400. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25401. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25402. return this;
  25403. };
  25404. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25405. if (!BABYLON.PickingInfo) {
  25406. return null;
  25407. }
  25408. var pickingInfo = null;
  25409. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25410. var mesh = this.meshes[meshIndex];
  25411. if (predicate) {
  25412. if (!predicate(mesh)) {
  25413. continue;
  25414. }
  25415. }
  25416. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25417. continue;
  25418. }
  25419. var world = mesh.getWorldMatrix();
  25420. var ray = rayFunction(world);
  25421. var result = mesh.intersects(ray, fastCheck);
  25422. if (!result || !result.hit)
  25423. continue;
  25424. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25425. continue;
  25426. pickingInfo = result;
  25427. if (fastCheck) {
  25428. break;
  25429. }
  25430. }
  25431. return pickingInfo || new BABYLON.PickingInfo();
  25432. };
  25433. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25434. if (!BABYLON.PickingInfo) {
  25435. return null;
  25436. }
  25437. var pickingInfos = new Array();
  25438. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25439. var mesh = this.meshes[meshIndex];
  25440. if (predicate) {
  25441. if (!predicate(mesh)) {
  25442. continue;
  25443. }
  25444. }
  25445. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25446. continue;
  25447. }
  25448. var world = mesh.getWorldMatrix();
  25449. var ray = rayFunction(world);
  25450. var result = mesh.intersects(ray, false);
  25451. if (!result || !result.hit)
  25452. continue;
  25453. pickingInfos.push(result);
  25454. }
  25455. return pickingInfos;
  25456. };
  25457. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25458. if (!BABYLON.PickingInfo) {
  25459. return null;
  25460. }
  25461. var pickingInfo = null;
  25462. if (!camera) {
  25463. if (!this.activeCamera) {
  25464. return null;
  25465. }
  25466. camera = this.activeCamera;
  25467. }
  25468. if (this.spriteManagers.length > 0) {
  25469. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25470. var spriteManager = this.spriteManagers[spriteIndex];
  25471. if (!spriteManager.isPickable) {
  25472. continue;
  25473. }
  25474. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25475. if (!result || !result.hit)
  25476. continue;
  25477. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25478. continue;
  25479. pickingInfo = result;
  25480. if (fastCheck) {
  25481. break;
  25482. }
  25483. }
  25484. }
  25485. return pickingInfo || new BABYLON.PickingInfo();
  25486. };
  25487. /** Launch a ray to try to pick a mesh in the scene
  25488. * @param x position on screen
  25489. * @param y position on screen
  25490. * @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
  25491. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25492. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25493. */
  25494. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25495. var _this = this;
  25496. if (!BABYLON.PickingInfo) {
  25497. return null;
  25498. }
  25499. return this._internalPick(function (world) {
  25500. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25501. return _this._tempPickingRay;
  25502. }, predicate, fastCheck);
  25503. };
  25504. /** Launch a ray to try to pick a sprite in the scene
  25505. * @param x position on screen
  25506. * @param y position on screen
  25507. * @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
  25508. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25509. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25510. */
  25511. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25512. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25513. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25514. };
  25515. /** Use the given ray to pick a mesh in the scene
  25516. * @param ray The ray to use to pick meshes
  25517. * @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
  25518. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25519. */
  25520. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25521. var _this = this;
  25522. return this._internalPick(function (world) {
  25523. if (!_this._pickWithRayInverseMatrix) {
  25524. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25525. }
  25526. world.invertToRef(_this._pickWithRayInverseMatrix);
  25527. if (!_this._cachedRayForTransform) {
  25528. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25529. }
  25530. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25531. return _this._cachedRayForTransform;
  25532. }, predicate, fastCheck);
  25533. };
  25534. /**
  25535. * Launch a ray to try to pick a mesh in the scene
  25536. * @param x X position on screen
  25537. * @param y Y position on screen
  25538. * @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
  25539. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25540. */
  25541. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25542. var _this = this;
  25543. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25544. };
  25545. /**
  25546. * Launch a ray to try to pick a mesh in the scene
  25547. * @param ray Ray to use
  25548. * @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
  25549. */
  25550. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25551. var _this = this;
  25552. return this._internalMultiPick(function (world) {
  25553. if (!_this._pickWithRayInverseMatrix) {
  25554. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25555. }
  25556. world.invertToRef(_this._pickWithRayInverseMatrix);
  25557. if (!_this._cachedRayForTransform) {
  25558. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25559. }
  25560. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25561. return _this._cachedRayForTransform;
  25562. }, predicate);
  25563. };
  25564. Scene.prototype.setPointerOverMesh = function (mesh) {
  25565. if (this._pointerOverMesh === mesh) {
  25566. return;
  25567. }
  25568. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25569. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25570. }
  25571. this._pointerOverMesh = mesh;
  25572. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25573. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25574. }
  25575. };
  25576. Scene.prototype.getPointerOverMesh = function () {
  25577. return this._pointerOverMesh;
  25578. };
  25579. Scene.prototype.setPointerOverSprite = function (sprite) {
  25580. if (this._pointerOverSprite === sprite) {
  25581. return;
  25582. }
  25583. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25584. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25585. }
  25586. this._pointerOverSprite = sprite;
  25587. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25588. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25589. }
  25590. };
  25591. Scene.prototype.getPointerOverSprite = function () {
  25592. return this._pointerOverSprite;
  25593. };
  25594. // Physics
  25595. Scene.prototype.getPhysicsEngine = function () {
  25596. return this._physicsEngine;
  25597. };
  25598. /**
  25599. * Enables physics to the current scene
  25600. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25601. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25602. * @return {boolean} was the physics engine initialized
  25603. */
  25604. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25605. if (gravity === void 0) { gravity = null; }
  25606. if (this._physicsEngine) {
  25607. return true;
  25608. }
  25609. try {
  25610. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25611. return true;
  25612. }
  25613. catch (e) {
  25614. BABYLON.Tools.Error(e.message);
  25615. return false;
  25616. }
  25617. };
  25618. Scene.prototype.disablePhysicsEngine = function () {
  25619. if (!this._physicsEngine) {
  25620. return;
  25621. }
  25622. this._physicsEngine.dispose();
  25623. this._physicsEngine = null;
  25624. };
  25625. Scene.prototype.isPhysicsEnabled = function () {
  25626. return this._physicsEngine !== undefined;
  25627. };
  25628. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25629. var mesh = compound.parts[0].mesh;
  25630. if (mesh.physicsImpostor) {
  25631. mesh.physicsImpostor.dispose();
  25632. mesh.physicsImpostor = null;
  25633. }
  25634. };
  25635. // Misc.
  25636. Scene.prototype._rebuildGeometries = function () {
  25637. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25638. var geometry = _a[_i];
  25639. geometry._rebuild();
  25640. }
  25641. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25642. var mesh = _c[_b];
  25643. mesh._rebuild();
  25644. }
  25645. if (this.postProcessManager) {
  25646. this.postProcessManager._rebuild();
  25647. }
  25648. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25649. var layer = _e[_d];
  25650. layer._rebuild();
  25651. }
  25652. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25653. var effectLayer = _g[_f];
  25654. effectLayer._rebuild();
  25655. }
  25656. if (this._boundingBoxRenderer) {
  25657. this._boundingBoxRenderer._rebuild();
  25658. }
  25659. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25660. var system = _j[_h];
  25661. system.rebuild();
  25662. }
  25663. if (this._postProcessRenderPipelineManager) {
  25664. this._postProcessRenderPipelineManager._rebuild();
  25665. }
  25666. };
  25667. Scene.prototype._rebuildTextures = function () {
  25668. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25669. var texture = _a[_i];
  25670. texture._rebuild();
  25671. }
  25672. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25673. };
  25674. /**
  25675. * Creates a default light for the scene.
  25676. * @param replace Whether to replace the existing lights in the scene.
  25677. */
  25678. Scene.prototype.createDefaultLight = function (replace) {
  25679. if (replace === void 0) { replace = false; }
  25680. // Dispose existing light in replace mode.
  25681. if (replace) {
  25682. if (this.lights) {
  25683. for (var i = 0; i < this.lights.length; i++) {
  25684. this.lights[i].dispose();
  25685. }
  25686. }
  25687. }
  25688. // Light
  25689. if (this.lights.length === 0) {
  25690. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25691. }
  25692. };
  25693. /**
  25694. * Creates a default camera for the scene.
  25695. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25696. * @param replace Whether to replace the existing active camera in the scene.
  25697. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25698. */
  25699. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25700. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25701. if (replace === void 0) { replace = false; }
  25702. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25703. // Dispose existing camera in replace mode.
  25704. if (replace) {
  25705. if (this.activeCamera) {
  25706. this.activeCamera.dispose();
  25707. this.activeCamera = null;
  25708. }
  25709. }
  25710. // Camera
  25711. if (!this.activeCamera) {
  25712. var worldExtends = this.getWorldExtends();
  25713. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25714. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25715. var camera;
  25716. var radius = worldSize.length() * 1.5;
  25717. // empty scene scenario!
  25718. if (!isFinite(radius)) {
  25719. radius = 1;
  25720. worldCenter.copyFromFloats(0, 0, 0);
  25721. }
  25722. if (createArcRotateCamera) {
  25723. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25724. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25725. arcRotateCamera.wheelPrecision = 100 / radius;
  25726. camera = arcRotateCamera;
  25727. }
  25728. else {
  25729. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25730. freeCamera.setTarget(worldCenter);
  25731. camera = freeCamera;
  25732. }
  25733. camera.minZ = radius * 0.01;
  25734. camera.maxZ = radius * 1000;
  25735. camera.speed = radius * 0.2;
  25736. this.activeCamera = camera;
  25737. var canvas = this.getEngine().getRenderingCanvas();
  25738. if (attachCameraControls && canvas) {
  25739. camera.attachControl(canvas);
  25740. }
  25741. }
  25742. };
  25743. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25744. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25745. if (replace === void 0) { replace = false; }
  25746. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25747. this.createDefaultLight(replace);
  25748. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25749. };
  25750. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25751. if (pbr === void 0) { pbr = false; }
  25752. if (scale === void 0) { scale = 1000; }
  25753. if (blur === void 0) { blur = 0; }
  25754. if (environmentTexture) {
  25755. this.environmentTexture = environmentTexture;
  25756. }
  25757. if (!this.environmentTexture) {
  25758. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25759. return null;
  25760. }
  25761. // Skybox
  25762. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25763. if (pbr) {
  25764. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25765. hdrSkyboxMaterial.backFaceCulling = false;
  25766. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25767. if (hdrSkyboxMaterial.reflectionTexture) {
  25768. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25769. }
  25770. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25771. hdrSkyboxMaterial.disableLighting = true;
  25772. hdrSkyboxMaterial.twoSidedLighting = true;
  25773. hdrSkybox.infiniteDistance = true;
  25774. hdrSkybox.material = hdrSkyboxMaterial;
  25775. }
  25776. else {
  25777. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25778. skyboxMaterial.backFaceCulling = false;
  25779. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25780. if (skyboxMaterial.reflectionTexture) {
  25781. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25782. }
  25783. skyboxMaterial.disableLighting = true;
  25784. hdrSkybox.infiniteDistance = true;
  25785. hdrSkybox.material = skyboxMaterial;
  25786. }
  25787. return hdrSkybox;
  25788. };
  25789. Scene.prototype.createDefaultEnvironment = function (options) {
  25790. if (BABYLON.EnvironmentHelper) {
  25791. return new BABYLON.EnvironmentHelper(options, this);
  25792. }
  25793. return null;
  25794. };
  25795. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25796. if (webVROptions === void 0) { webVROptions = {}; }
  25797. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25798. };
  25799. // Tags
  25800. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25801. if (tagsQuery === undefined) {
  25802. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25803. return list;
  25804. }
  25805. var listByTags = [];
  25806. forEach = forEach || (function (item) { return; });
  25807. for (var i in list) {
  25808. var item = list[i];
  25809. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25810. listByTags.push(item);
  25811. forEach(item);
  25812. }
  25813. }
  25814. return listByTags;
  25815. };
  25816. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25817. return this._getByTags(this.meshes, tagsQuery, forEach);
  25818. };
  25819. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25820. return this._getByTags(this.cameras, tagsQuery, forEach);
  25821. };
  25822. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25823. return this._getByTags(this.lights, tagsQuery, forEach);
  25824. };
  25825. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25826. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25827. };
  25828. /**
  25829. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25830. * This allowed control for front to back rendering or reversly depending of the special needs.
  25831. *
  25832. * @param renderingGroupId The rendering group id corresponding to its index
  25833. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25834. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25835. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25836. */
  25837. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25838. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25839. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25840. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25841. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25842. };
  25843. /**
  25844. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25845. *
  25846. * @param renderingGroupId The rendering group id corresponding to its index
  25847. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25848. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25849. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25850. */
  25851. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25852. if (depth === void 0) { depth = true; }
  25853. if (stencil === void 0) { stencil = true; }
  25854. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25855. };
  25856. /**
  25857. * Will flag all materials as dirty to trigger new shader compilation
  25858. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25859. */
  25860. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25861. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25862. var material = _a[_i];
  25863. if (predicate && !predicate(material)) {
  25864. continue;
  25865. }
  25866. material.markAsDirty(flag);
  25867. }
  25868. };
  25869. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25870. var _this = this;
  25871. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25872. this._activeRequests.push(request);
  25873. request.onCompleteObservable.add(function (request) {
  25874. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25875. });
  25876. return request;
  25877. };
  25878. /** @ignore */
  25879. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25880. var _this = this;
  25881. return new Promise(function (resolve, reject) {
  25882. _this._loadFile(url, function (data) {
  25883. resolve(data);
  25884. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25885. reject(exception);
  25886. });
  25887. });
  25888. };
  25889. // Statics
  25890. Scene._FOGMODE_NONE = 0;
  25891. Scene._FOGMODE_EXP = 1;
  25892. Scene._FOGMODE_EXP2 = 2;
  25893. Scene._FOGMODE_LINEAR = 3;
  25894. Scene._uniqueIdCounter = 0;
  25895. Scene.MinDeltaTime = 1.0;
  25896. Scene.MaxDeltaTime = 1000.0;
  25897. /** The distance in pixel that you have to move to prevent some events */
  25898. Scene.DragMovementThreshold = 10; // in pixels
  25899. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25900. Scene.LongPressDelay = 500; // in milliseconds
  25901. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25902. Scene.DoubleClickDelay = 300; // in milliseconds
  25903. /** If you need to check double click without raising a single click at first click, enable this flag */
  25904. Scene.ExclusiveDoubleClickMode = false;
  25905. return Scene;
  25906. }());
  25907. BABYLON.Scene = Scene;
  25908. })(BABYLON || (BABYLON = {}));
  25909. //# sourceMappingURL=babylon.scene.js.map
  25910. "use strict";
  25911. var BABYLON;
  25912. (function (BABYLON) {
  25913. /**
  25914. * Set of assets to keep when moving a scene into an asset container.
  25915. */
  25916. var KeepAssets = /** @class */ (function () {
  25917. function KeepAssets() {
  25918. /**
  25919. * Cameras to keep.
  25920. */
  25921. this.cameras = new Array();
  25922. /**
  25923. * Lights to keep.
  25924. */
  25925. this.lights = new Array();
  25926. /**
  25927. * Meshes to keep.
  25928. */
  25929. this.meshes = new Array();
  25930. /**
  25931. * Skeletons to keep.
  25932. */
  25933. this.skeletons = new Array();
  25934. /**
  25935. * ParticleSystems to keep.
  25936. */
  25937. this.particleSystems = new Array();
  25938. /**
  25939. * Animations to keep.
  25940. */
  25941. this.animations = new Array();
  25942. /**
  25943. * MultiMaterials to keep.
  25944. */
  25945. this.multiMaterials = new Array();
  25946. /**
  25947. * Materials to keep.
  25948. */
  25949. this.materials = new Array();
  25950. /**
  25951. * MorphTargetManagers to keep.
  25952. */
  25953. this.morphTargetManagers = new Array();
  25954. /**
  25955. * Geometries to keep.
  25956. */
  25957. this.geometries = new Array();
  25958. /**
  25959. * TransformNodes to keep.
  25960. */
  25961. this.transformNodes = new Array();
  25962. /**
  25963. * LensFlareSystems to keep.
  25964. */
  25965. this.lensFlareSystems = new Array();
  25966. /**
  25967. * ShadowGenerators to keep.
  25968. */
  25969. this.shadowGenerators = new Array();
  25970. /**
  25971. * ActionManagers to keep.
  25972. */
  25973. this.actionManagers = new Array();
  25974. /**
  25975. * Sounds to keep.
  25976. */
  25977. this.sounds = new Array();
  25978. }
  25979. return KeepAssets;
  25980. }());
  25981. BABYLON.KeepAssets = KeepAssets;
  25982. /**
  25983. * Container with a set of assets that can be added or removed from a scene.
  25984. */
  25985. var AssetContainer = /** @class */ (function () {
  25986. /**
  25987. * Instantiates an AssetContainer.
  25988. * @param scene The scene the AssetContainer belongs to.
  25989. */
  25990. function AssetContainer(scene) {
  25991. // Objects
  25992. /**
  25993. * Cameras populated in the container.
  25994. */
  25995. this.cameras = new Array();
  25996. /**
  25997. * Lights populated in the container.
  25998. */
  25999. this.lights = new Array();
  26000. /**
  26001. * Meshes populated in the container.
  26002. */
  26003. this.meshes = new Array();
  26004. /**
  26005. * Skeletons populated in the container.
  26006. */
  26007. this.skeletons = new Array();
  26008. /**
  26009. * ParticleSystems populated in the container.
  26010. */
  26011. this.particleSystems = new Array();
  26012. /**
  26013. * Animations populated in the container.
  26014. */
  26015. this.animations = new Array();
  26016. /**
  26017. * MultiMaterials populated in the container.
  26018. */
  26019. this.multiMaterials = new Array();
  26020. /**
  26021. * Materials populated in the container.
  26022. */
  26023. this.materials = new Array();
  26024. /**
  26025. * MorphTargetManagers populated in the container.
  26026. */
  26027. this.morphTargetManagers = new Array();
  26028. /**
  26029. * Geometries populated in the container.
  26030. */
  26031. this.geometries = new Array();
  26032. /**
  26033. * TransformNodes populated in the container.
  26034. */
  26035. this.transformNodes = new Array();
  26036. /**
  26037. * LensFlareSystems populated in the container.
  26038. */
  26039. this.lensFlareSystems = new Array();
  26040. /**
  26041. * ShadowGenerators populated in the container.
  26042. */
  26043. this.shadowGenerators = new Array();
  26044. /**
  26045. * ActionManagers populated in the container.
  26046. */
  26047. this.actionManagers = new Array();
  26048. /**
  26049. * Sounds populated in the container.
  26050. */
  26051. this.sounds = new Array();
  26052. this.scene = scene;
  26053. }
  26054. /**
  26055. * Adds all the assets from the container to the scene.
  26056. */
  26057. AssetContainer.prototype.addAllToScene = function () {
  26058. var _this = this;
  26059. this.cameras.forEach(function (o) {
  26060. _this.scene.addCamera(o);
  26061. });
  26062. this.lights.forEach(function (o) {
  26063. _this.scene.addLight(o);
  26064. });
  26065. this.meshes.forEach(function (o) {
  26066. _this.scene.addMesh(o);
  26067. });
  26068. this.skeletons.forEach(function (o) {
  26069. _this.scene.addSkeleton(o);
  26070. });
  26071. this.particleSystems.forEach(function (o) {
  26072. _this.scene.addParticleSystem(o);
  26073. });
  26074. this.animations.forEach(function (o) {
  26075. _this.scene.addAnimation(o);
  26076. });
  26077. this.multiMaterials.forEach(function (o) {
  26078. _this.scene.addMultiMaterial(o);
  26079. });
  26080. this.materials.forEach(function (o) {
  26081. _this.scene.addMaterial(o);
  26082. });
  26083. this.morphTargetManagers.forEach(function (o) {
  26084. _this.scene.addMorphTargetManager(o);
  26085. });
  26086. this.geometries.forEach(function (o) {
  26087. _this.scene.addGeometry(o);
  26088. });
  26089. this.transformNodes.forEach(function (o) {
  26090. _this.scene.addTransformNode(o);
  26091. });
  26092. this.lensFlareSystems.forEach(function (o) {
  26093. _this.scene.addLensFlareSystem(o);
  26094. });
  26095. this.actionManagers.forEach(function (o) {
  26096. _this.scene.addActionManager(o);
  26097. });
  26098. this.sounds.forEach(function (o) {
  26099. o.play();
  26100. o.autoplay = true;
  26101. _this.scene.mainSoundTrack.AddSound(o);
  26102. });
  26103. };
  26104. /**
  26105. * Removes all the assets in the container from the scene
  26106. */
  26107. AssetContainer.prototype.removeAllFromScene = function () {
  26108. var _this = this;
  26109. this.cameras.forEach(function (o) {
  26110. _this.scene.removeCamera(o);
  26111. });
  26112. this.lights.forEach(function (o) {
  26113. _this.scene.removeLight(o);
  26114. });
  26115. this.meshes.forEach(function (o) {
  26116. _this.scene.removeMesh(o);
  26117. });
  26118. this.skeletons.forEach(function (o) {
  26119. _this.scene.removeSkeleton(o);
  26120. });
  26121. this.particleSystems.forEach(function (o) {
  26122. _this.scene.removeParticleSystem(o);
  26123. });
  26124. this.animations.forEach(function (o) {
  26125. _this.scene.removeAnimation(o);
  26126. });
  26127. this.multiMaterials.forEach(function (o) {
  26128. _this.scene.removeMultiMaterial(o);
  26129. });
  26130. this.materials.forEach(function (o) {
  26131. _this.scene.removeMaterial(o);
  26132. });
  26133. this.morphTargetManagers.forEach(function (o) {
  26134. _this.scene.removeMorphTargetManager(o);
  26135. });
  26136. this.geometries.forEach(function (o) {
  26137. _this.scene.removeGeometry(o);
  26138. });
  26139. this.transformNodes.forEach(function (o) {
  26140. _this.scene.removeTransformNode(o);
  26141. });
  26142. this.lensFlareSystems.forEach(function (o) {
  26143. _this.scene.removeLensFlareSystem(o);
  26144. });
  26145. this.actionManagers.forEach(function (o) {
  26146. _this.scene.removeActionManager(o);
  26147. });
  26148. this.sounds.forEach(function (o) {
  26149. o.stop();
  26150. o.autoplay = false;
  26151. _this.scene.mainSoundTrack.RemoveSound(o);
  26152. });
  26153. };
  26154. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26155. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26156. var asset = sourceAssets_1[_i];
  26157. var move = true;
  26158. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26159. var keepAsset = keepAssets_1[_a];
  26160. if (asset === keepAsset) {
  26161. move = false;
  26162. break;
  26163. }
  26164. }
  26165. if (move) {
  26166. targetAssets.push(asset);
  26167. }
  26168. }
  26169. };
  26170. /**
  26171. * Removes all the assets contained in the scene and adds them to the container.
  26172. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26173. */
  26174. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26175. if (keepAssets === undefined) {
  26176. keepAssets = new KeepAssets();
  26177. }
  26178. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26179. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26180. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26181. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26182. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26183. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26184. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26185. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26186. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26187. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26188. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26189. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26190. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26191. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26192. this.removeAllFromScene();
  26193. };
  26194. return AssetContainer;
  26195. }());
  26196. BABYLON.AssetContainer = AssetContainer;
  26197. })(BABYLON || (BABYLON = {}));
  26198. //# sourceMappingURL=babylon.assetContainer.js.map
  26199. "use strict";
  26200. var BABYLON;
  26201. (function (BABYLON) {
  26202. var Buffer = /** @class */ (function () {
  26203. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26204. if (instanced === void 0) { instanced = false; }
  26205. if (engine instanceof BABYLON.Mesh) {
  26206. this._engine = engine.getScene().getEngine();
  26207. }
  26208. else {
  26209. this._engine = engine;
  26210. }
  26211. this._updatable = updatable;
  26212. this._instanced = instanced;
  26213. this._data = data;
  26214. this._strideSize = stride;
  26215. if (!postponeInternalCreation) {
  26216. this.create();
  26217. }
  26218. }
  26219. /**
  26220. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26221. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26222. * @param offset defines offset in the buffer (0 by default)
  26223. * @param size defines the size in floats of attributes (position is 3 for instance)
  26224. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26225. * @param instanced defines if the vertex buffer contains indexed data
  26226. * @returns the new vertex buffer
  26227. */
  26228. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26229. // a lot of these parameters are ignored as they are overriden by the buffer
  26230. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26231. };
  26232. // Properties
  26233. Buffer.prototype.isUpdatable = function () {
  26234. return this._updatable;
  26235. };
  26236. Buffer.prototype.getData = function () {
  26237. return this._data;
  26238. };
  26239. Buffer.prototype.getBuffer = function () {
  26240. return this._buffer;
  26241. };
  26242. Buffer.prototype.getStrideSize = function () {
  26243. return this._strideSize;
  26244. };
  26245. // public getIsInstanced(): boolean {
  26246. // return this._instanced;
  26247. // }
  26248. // public get instanceDivisor(): number {
  26249. // return this._instanceDivisor;
  26250. // }
  26251. // public set instanceDivisor(value: number) {
  26252. // this._instanceDivisor = value;
  26253. // if (value == 0) {
  26254. // this._instanced = false;
  26255. // } else {
  26256. // this._instanced = true;
  26257. // }
  26258. // }
  26259. // Methods
  26260. Buffer.prototype.create = function (data) {
  26261. if (data === void 0) { data = null; }
  26262. if (!data && this._buffer) {
  26263. return; // nothing to do
  26264. }
  26265. data = data || this._data;
  26266. if (!data) {
  26267. return;
  26268. }
  26269. if (!this._buffer) {
  26270. if (this._updatable) {
  26271. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26272. this._data = data;
  26273. }
  26274. else {
  26275. this._buffer = this._engine.createVertexBuffer(data);
  26276. }
  26277. }
  26278. else if (this._updatable) {
  26279. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26280. this._data = data;
  26281. }
  26282. };
  26283. Buffer.prototype._rebuild = function () {
  26284. this._buffer = null;
  26285. this.create(this._data);
  26286. };
  26287. Buffer.prototype.update = function (data) {
  26288. this.create(data);
  26289. };
  26290. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26291. if (!this._buffer) {
  26292. return;
  26293. }
  26294. if (this._updatable) {
  26295. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26296. this._data = null;
  26297. }
  26298. };
  26299. Buffer.prototype.dispose = function () {
  26300. if (!this._buffer) {
  26301. return;
  26302. }
  26303. if (this._engine._releaseBuffer(this._buffer)) {
  26304. this._buffer = null;
  26305. }
  26306. };
  26307. return Buffer;
  26308. }());
  26309. BABYLON.Buffer = Buffer;
  26310. })(BABYLON || (BABYLON = {}));
  26311. //# sourceMappingURL=babylon.buffer.js.map
  26312. "use strict";
  26313. var BABYLON;
  26314. (function (BABYLON) {
  26315. var VertexBuffer = /** @class */ (function () {
  26316. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26317. if (data instanceof BABYLON.Buffer) {
  26318. if (!stride) {
  26319. stride = data.getStrideSize();
  26320. }
  26321. this._buffer = data;
  26322. this._ownsBuffer = false;
  26323. }
  26324. else {
  26325. if (!stride) {
  26326. stride = VertexBuffer.DeduceStride(kind);
  26327. }
  26328. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26329. this._ownsBuffer = true;
  26330. }
  26331. this._stride = stride;
  26332. this._instanced = instanced !== undefined ? instanced : false;
  26333. this._instanceDivisor = instanced ? 1 : 0;
  26334. this._offset = offset ? offset : 0;
  26335. this._size = size ? size : stride;
  26336. this._kind = kind;
  26337. }
  26338. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26339. /**
  26340. * Gets or sets the instance divisor when in instanced mode
  26341. */
  26342. get: function () {
  26343. return this._instanceDivisor;
  26344. },
  26345. set: function (value) {
  26346. this._instanceDivisor = value;
  26347. if (value == 0) {
  26348. this._instanced = false;
  26349. }
  26350. else {
  26351. this._instanced = true;
  26352. }
  26353. },
  26354. enumerable: true,
  26355. configurable: true
  26356. });
  26357. VertexBuffer.prototype._rebuild = function () {
  26358. if (!this._buffer) {
  26359. return;
  26360. }
  26361. this._buffer._rebuild();
  26362. };
  26363. /**
  26364. * Returns the kind of the VertexBuffer (string).
  26365. */
  26366. VertexBuffer.prototype.getKind = function () {
  26367. return this._kind;
  26368. };
  26369. // Properties
  26370. /**
  26371. * Boolean : is the VertexBuffer updatable ?
  26372. */
  26373. VertexBuffer.prototype.isUpdatable = function () {
  26374. return this._buffer.isUpdatable();
  26375. };
  26376. /**
  26377. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26378. */
  26379. VertexBuffer.prototype.getData = function () {
  26380. return this._buffer.getData();
  26381. };
  26382. /**
  26383. * Returns the WebGLBuffer associated to the VertexBuffer.
  26384. */
  26385. VertexBuffer.prototype.getBuffer = function () {
  26386. return this._buffer.getBuffer();
  26387. };
  26388. /**
  26389. * Returns the stride of the VertexBuffer (integer).
  26390. */
  26391. VertexBuffer.prototype.getStrideSize = function () {
  26392. return this._stride;
  26393. };
  26394. /**
  26395. * Returns the offset (integer).
  26396. */
  26397. VertexBuffer.prototype.getOffset = function () {
  26398. return this._offset;
  26399. };
  26400. /**
  26401. * Returns the VertexBuffer total size (integer).
  26402. */
  26403. VertexBuffer.prototype.getSize = function () {
  26404. return this._size;
  26405. };
  26406. /**
  26407. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26408. */
  26409. VertexBuffer.prototype.getIsInstanced = function () {
  26410. return this._instanced;
  26411. };
  26412. /**
  26413. * Returns the instancing divisor, zero for non-instanced (integer).
  26414. */
  26415. VertexBuffer.prototype.getInstanceDivisor = function () {
  26416. return this._instanceDivisor;
  26417. };
  26418. // Methods
  26419. /**
  26420. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26421. * Returns the created WebGLBuffer.
  26422. */
  26423. VertexBuffer.prototype.create = function (data) {
  26424. return this._buffer.create(data);
  26425. };
  26426. /**
  26427. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26428. * This function will create a new buffer if the current one is not updatable
  26429. * Returns the updated WebGLBuffer.
  26430. */
  26431. VertexBuffer.prototype.update = function (data) {
  26432. return this._buffer.update(data);
  26433. };
  26434. /**
  26435. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26436. * Returns the directly updated WebGLBuffer.
  26437. */
  26438. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26439. return this._buffer.updateDirectly(data, offset);
  26440. };
  26441. /**
  26442. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26443. */
  26444. VertexBuffer.prototype.dispose = function () {
  26445. if (this._ownsBuffer) {
  26446. this._buffer.dispose();
  26447. }
  26448. };
  26449. Object.defineProperty(VertexBuffer, "PositionKind", {
  26450. get: function () {
  26451. return VertexBuffer._PositionKind;
  26452. },
  26453. enumerable: true,
  26454. configurable: true
  26455. });
  26456. Object.defineProperty(VertexBuffer, "NormalKind", {
  26457. get: function () {
  26458. return VertexBuffer._NormalKind;
  26459. },
  26460. enumerable: true,
  26461. configurable: true
  26462. });
  26463. Object.defineProperty(VertexBuffer, "TangentKind", {
  26464. get: function () {
  26465. return VertexBuffer._TangentKind;
  26466. },
  26467. enumerable: true,
  26468. configurable: true
  26469. });
  26470. Object.defineProperty(VertexBuffer, "UVKind", {
  26471. get: function () {
  26472. return VertexBuffer._UVKind;
  26473. },
  26474. enumerable: true,
  26475. configurable: true
  26476. });
  26477. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26478. get: function () {
  26479. return VertexBuffer._UV2Kind;
  26480. },
  26481. enumerable: true,
  26482. configurable: true
  26483. });
  26484. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26485. get: function () {
  26486. return VertexBuffer._UV3Kind;
  26487. },
  26488. enumerable: true,
  26489. configurable: true
  26490. });
  26491. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26492. get: function () {
  26493. return VertexBuffer._UV4Kind;
  26494. },
  26495. enumerable: true,
  26496. configurable: true
  26497. });
  26498. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26499. get: function () {
  26500. return VertexBuffer._UV5Kind;
  26501. },
  26502. enumerable: true,
  26503. configurable: true
  26504. });
  26505. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26506. get: function () {
  26507. return VertexBuffer._UV6Kind;
  26508. },
  26509. enumerable: true,
  26510. configurable: true
  26511. });
  26512. Object.defineProperty(VertexBuffer, "ColorKind", {
  26513. get: function () {
  26514. return VertexBuffer._ColorKind;
  26515. },
  26516. enumerable: true,
  26517. configurable: true
  26518. });
  26519. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26520. get: function () {
  26521. return VertexBuffer._MatricesIndicesKind;
  26522. },
  26523. enumerable: true,
  26524. configurable: true
  26525. });
  26526. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26527. get: function () {
  26528. return VertexBuffer._MatricesWeightsKind;
  26529. },
  26530. enumerable: true,
  26531. configurable: true
  26532. });
  26533. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26534. get: function () {
  26535. return VertexBuffer._MatricesIndicesExtraKind;
  26536. },
  26537. enumerable: true,
  26538. configurable: true
  26539. });
  26540. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26541. get: function () {
  26542. return VertexBuffer._MatricesWeightsExtraKind;
  26543. },
  26544. enumerable: true,
  26545. configurable: true
  26546. });
  26547. /**
  26548. * Deduces the stride given a kind.
  26549. * @param kind The kind string to deduce
  26550. * @returns The deduced stride
  26551. */
  26552. VertexBuffer.DeduceStride = function (kind) {
  26553. switch (kind) {
  26554. case VertexBuffer.UVKind:
  26555. case VertexBuffer.UV2Kind:
  26556. case VertexBuffer.UV3Kind:
  26557. case VertexBuffer.UV4Kind:
  26558. case VertexBuffer.UV5Kind:
  26559. case VertexBuffer.UV6Kind:
  26560. return 2;
  26561. case VertexBuffer.NormalKind:
  26562. case VertexBuffer.PositionKind:
  26563. return 3;
  26564. case VertexBuffer.ColorKind:
  26565. case VertexBuffer.MatricesIndicesKind:
  26566. case VertexBuffer.MatricesIndicesExtraKind:
  26567. case VertexBuffer.MatricesWeightsKind:
  26568. case VertexBuffer.MatricesWeightsExtraKind:
  26569. case VertexBuffer.TangentKind:
  26570. return 4;
  26571. default:
  26572. throw new Error("Invalid kind '" + kind + "'");
  26573. }
  26574. };
  26575. // Enums
  26576. VertexBuffer._PositionKind = "position";
  26577. VertexBuffer._NormalKind = "normal";
  26578. VertexBuffer._TangentKind = "tangent";
  26579. VertexBuffer._UVKind = "uv";
  26580. VertexBuffer._UV2Kind = "uv2";
  26581. VertexBuffer._UV3Kind = "uv3";
  26582. VertexBuffer._UV4Kind = "uv4";
  26583. VertexBuffer._UV5Kind = "uv5";
  26584. VertexBuffer._UV6Kind = "uv6";
  26585. VertexBuffer._ColorKind = "color";
  26586. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26587. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26588. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26589. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26590. return VertexBuffer;
  26591. }());
  26592. BABYLON.VertexBuffer = VertexBuffer;
  26593. })(BABYLON || (BABYLON = {}));
  26594. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26595. "use strict";
  26596. var BABYLON;
  26597. (function (BABYLON) {
  26598. /**
  26599. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26600. */
  26601. var DummyInternalTextureTracker = /** @class */ (function () {
  26602. function DummyInternalTextureTracker() {
  26603. /**
  26604. * Gets or set the previous tracker in the list
  26605. */
  26606. this.previous = null;
  26607. /**
  26608. * Gets or set the next tracker in the list
  26609. */
  26610. this.next = null;
  26611. }
  26612. return DummyInternalTextureTracker;
  26613. }());
  26614. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26615. })(BABYLON || (BABYLON = {}));
  26616. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26617. "use strict";
  26618. var BABYLON;
  26619. (function (BABYLON) {
  26620. /**
  26621. * Class used to store data associated with WebGL texture data for the engine
  26622. * This class should not be used directly
  26623. */
  26624. var InternalTexture = /** @class */ (function () {
  26625. /**
  26626. * Creates a new InternalTexture
  26627. * @param engine defines the engine to use
  26628. * @param dataSource defines the type of data that will be used
  26629. */
  26630. function InternalTexture(engine, dataSource) {
  26631. /**
  26632. * Observable called when the texture is loaded
  26633. */
  26634. this.onLoadedObservable = new BABYLON.Observable();
  26635. /**
  26636. * Gets or set the previous tracker in the list
  26637. */
  26638. this.previous = null;
  26639. /**
  26640. * Gets or set the next tracker in the list
  26641. */
  26642. this.next = null;
  26643. // Private
  26644. /** @ignore */
  26645. this._initialSlot = -1;
  26646. /** @ignore */
  26647. this._designatedSlot = -1;
  26648. /** @ignore */
  26649. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26650. /** @ignore */
  26651. this._comparisonFunction = 0;
  26652. /** @ignore */
  26653. this._references = 1;
  26654. this._engine = engine;
  26655. this._dataSource = dataSource;
  26656. this._webGLTexture = engine._createTexture();
  26657. }
  26658. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26659. /**
  26660. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26661. */
  26662. get: function () {
  26663. return this._dataSource;
  26664. },
  26665. enumerable: true,
  26666. configurable: true
  26667. });
  26668. /**
  26669. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26670. */
  26671. InternalTexture.prototype.incrementReferences = function () {
  26672. this._references++;
  26673. };
  26674. /**
  26675. * Change the size of the texture (not the size of the content)
  26676. * @param width defines the new width
  26677. * @param height defines the new height
  26678. * @param depth defines the new depth (1 by default)
  26679. */
  26680. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26681. if (depth === void 0) { depth = 1; }
  26682. this.width = width;
  26683. this.height = height;
  26684. this.depth = depth;
  26685. this.baseWidth = width;
  26686. this.baseHeight = height;
  26687. this.baseDepth = depth;
  26688. this._size = width * height * depth;
  26689. };
  26690. /** @ignore */
  26691. InternalTexture.prototype._rebuild = function () {
  26692. var _this = this;
  26693. var proxy;
  26694. this.isReady = false;
  26695. this._cachedCoordinatesMode = null;
  26696. this._cachedWrapU = null;
  26697. this._cachedWrapV = null;
  26698. this._cachedAnisotropicFilteringLevel = null;
  26699. switch (this._dataSource) {
  26700. case InternalTexture.DATASOURCE_TEMP:
  26701. return;
  26702. case InternalTexture.DATASOURCE_URL:
  26703. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26704. _this.isReady = true;
  26705. }, null, this._buffer, undefined, this.format);
  26706. proxy._swapAndDie(this);
  26707. return;
  26708. case InternalTexture.DATASOURCE_RAW:
  26709. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26710. proxy._swapAndDie(this);
  26711. this.isReady = true;
  26712. return;
  26713. case InternalTexture.DATASOURCE_RAW3D:
  26714. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26715. proxy._swapAndDie(this);
  26716. this.isReady = true;
  26717. return;
  26718. case InternalTexture.DATASOURCE_DYNAMIC:
  26719. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26720. proxy._swapAndDie(this);
  26721. // The engine will make sure to update content so no need to flag it as isReady = true
  26722. return;
  26723. case InternalTexture.DATASOURCE_RENDERTARGET:
  26724. var options = new BABYLON.RenderTargetCreationOptions();
  26725. options.generateDepthBuffer = this._generateDepthBuffer;
  26726. options.generateMipMaps = this.generateMipMaps;
  26727. options.generateStencilBuffer = this._generateStencilBuffer;
  26728. options.samplingMode = this.samplingMode;
  26729. options.type = this.type;
  26730. if (this.isCube) {
  26731. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26732. }
  26733. else {
  26734. var size = {
  26735. width: this.width,
  26736. height: this.height
  26737. };
  26738. proxy = this._engine.createRenderTargetTexture(size, options);
  26739. }
  26740. proxy._swapAndDie(this);
  26741. this.isReady = true;
  26742. return;
  26743. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26744. var depthTextureOptions = {
  26745. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26746. comparisonFunction: this._comparisonFunction,
  26747. generateStencil: this._generateStencilBuffer,
  26748. isCube: this.isCube
  26749. };
  26750. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26751. proxy._swapAndDie(this);
  26752. this.isReady = true;
  26753. return;
  26754. case InternalTexture.DATASOURCE_CUBE:
  26755. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26756. _this.isReady = true;
  26757. }, null, this.format, this._extension);
  26758. proxy._swapAndDie(this);
  26759. return;
  26760. case InternalTexture.DATASOURCE_CUBERAW:
  26761. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26762. proxy._swapAndDie(this);
  26763. this.isReady = true;
  26764. return;
  26765. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26766. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26767. if (proxy) {
  26768. proxy._swapAndDie(_this);
  26769. }
  26770. _this.isReady = true;
  26771. }, null, this.format, this._extension);
  26772. return;
  26773. }
  26774. };
  26775. InternalTexture.prototype._swapAndDie = function (target) {
  26776. target._webGLTexture = this._webGLTexture;
  26777. if (this._framebuffer) {
  26778. target._framebuffer = this._framebuffer;
  26779. }
  26780. if (this._depthStencilBuffer) {
  26781. target._depthStencilBuffer = this._depthStencilBuffer;
  26782. }
  26783. if (this._lodTextureHigh) {
  26784. if (target._lodTextureHigh) {
  26785. target._lodTextureHigh.dispose();
  26786. }
  26787. target._lodTextureHigh = this._lodTextureHigh;
  26788. }
  26789. if (this._lodTextureMid) {
  26790. if (target._lodTextureMid) {
  26791. target._lodTextureMid.dispose();
  26792. }
  26793. target._lodTextureMid = this._lodTextureMid;
  26794. }
  26795. if (this._lodTextureLow) {
  26796. if (target._lodTextureLow) {
  26797. target._lodTextureLow.dispose();
  26798. }
  26799. target._lodTextureLow = this._lodTextureLow;
  26800. }
  26801. var cache = this._engine.getLoadedTexturesCache();
  26802. var index = cache.indexOf(this);
  26803. if (index !== -1) {
  26804. cache.splice(index, 1);
  26805. }
  26806. };
  26807. /**
  26808. * Dispose the current allocated resources
  26809. */
  26810. InternalTexture.prototype.dispose = function () {
  26811. if (!this._webGLTexture) {
  26812. return;
  26813. }
  26814. this._references--;
  26815. if (this._references === 0) {
  26816. this._engine._releaseTexture(this);
  26817. this._webGLTexture = null;
  26818. this.previous = null;
  26819. this.next = null;
  26820. }
  26821. };
  26822. /**
  26823. * The source of the texture data is unknown
  26824. */
  26825. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26826. /**
  26827. * Texture data comes from an URL
  26828. */
  26829. InternalTexture.DATASOURCE_URL = 1;
  26830. /**
  26831. * Texture data is only used for temporary storage
  26832. */
  26833. InternalTexture.DATASOURCE_TEMP = 2;
  26834. /**
  26835. * Texture data comes from raw data (ArrayBuffer)
  26836. */
  26837. InternalTexture.DATASOURCE_RAW = 3;
  26838. /**
  26839. * Texture content is dynamic (video or dynamic texture)
  26840. */
  26841. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26842. /**
  26843. * Texture content is generated by rendering to it
  26844. */
  26845. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26846. /**
  26847. * Texture content is part of a multi render target process
  26848. */
  26849. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26850. /**
  26851. * Texture data comes from a cube data file
  26852. */
  26853. InternalTexture.DATASOURCE_CUBE = 7;
  26854. /**
  26855. * Texture data comes from a raw cube data
  26856. */
  26857. InternalTexture.DATASOURCE_CUBERAW = 8;
  26858. /**
  26859. * Texture data come from a prefiltered cube data file
  26860. */
  26861. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26862. /**
  26863. * Texture content is raw 3D data
  26864. */
  26865. InternalTexture.DATASOURCE_RAW3D = 10;
  26866. /**
  26867. * Texture content is a depth texture
  26868. */
  26869. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26870. return InternalTexture;
  26871. }());
  26872. BABYLON.InternalTexture = InternalTexture;
  26873. })(BABYLON || (BABYLON = {}));
  26874. //# sourceMappingURL=babylon.internalTexture.js.map
  26875. "use strict";
  26876. var BABYLON;
  26877. (function (BABYLON) {
  26878. var BaseTexture = /** @class */ (function () {
  26879. function BaseTexture(scene) {
  26880. this._hasAlpha = false;
  26881. this.getAlphaFromRGB = false;
  26882. this.level = 1;
  26883. this.coordinatesIndex = 0;
  26884. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26885. /**
  26886. * | Value | Type | Description |
  26887. * | ----- | ------------------ | ----------- |
  26888. * | 0 | CLAMP_ADDRESSMODE | |
  26889. * | 1 | WRAP_ADDRESSMODE | |
  26890. * | 2 | MIRROR_ADDRESSMODE | |
  26891. */
  26892. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26893. /**
  26894. * | Value | Type | Description |
  26895. * | ----- | ------------------ | ----------- |
  26896. * | 0 | CLAMP_ADDRESSMODE | |
  26897. * | 1 | WRAP_ADDRESSMODE | |
  26898. * | 2 | MIRROR_ADDRESSMODE | |
  26899. */
  26900. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26901. /**
  26902. * | Value | Type | Description |
  26903. * | ----- | ------------------ | ----------- |
  26904. * | 0 | CLAMP_ADDRESSMODE | |
  26905. * | 1 | WRAP_ADDRESSMODE | |
  26906. * | 2 | MIRROR_ADDRESSMODE | |
  26907. */
  26908. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26909. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26910. this.isCube = false;
  26911. this.is3D = false;
  26912. this.gammaSpace = true;
  26913. this.invertZ = false;
  26914. this.lodLevelInAlpha = false;
  26915. this.lodGenerationOffset = 0.0;
  26916. this.lodGenerationScale = 0.8;
  26917. this.isRenderTarget = false;
  26918. this.animations = new Array();
  26919. /**
  26920. * An event triggered when the texture is disposed.
  26921. * @type {BABYLON.Observable}
  26922. */
  26923. this.onDisposeObservable = new BABYLON.Observable();
  26924. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26925. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26926. if (this._scene) {
  26927. this._scene.textures.push(this);
  26928. }
  26929. this._uid = null;
  26930. }
  26931. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26932. get: function () {
  26933. return this._hasAlpha;
  26934. },
  26935. set: function (value) {
  26936. if (this._hasAlpha === value) {
  26937. return;
  26938. }
  26939. this._hasAlpha = value;
  26940. if (this._scene) {
  26941. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26942. }
  26943. },
  26944. enumerable: true,
  26945. configurable: true
  26946. });
  26947. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26948. get: function () {
  26949. return this._coordinatesMode;
  26950. },
  26951. /**
  26952. * How a texture is mapped.
  26953. *
  26954. * | Value | Type | Description |
  26955. * | ----- | ----------------------------------- | ----------- |
  26956. * | 0 | EXPLICIT_MODE | |
  26957. * | 1 | SPHERICAL_MODE | |
  26958. * | 2 | PLANAR_MODE | |
  26959. * | 3 | CUBIC_MODE | |
  26960. * | 4 | PROJECTION_MODE | |
  26961. * | 5 | SKYBOX_MODE | |
  26962. * | 6 | INVCUBIC_MODE | |
  26963. * | 7 | EQUIRECTANGULAR_MODE | |
  26964. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26965. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26966. */
  26967. set: function (value) {
  26968. if (this._coordinatesMode === value) {
  26969. return;
  26970. }
  26971. this._coordinatesMode = value;
  26972. if (this._scene) {
  26973. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26974. }
  26975. },
  26976. enumerable: true,
  26977. configurable: true
  26978. });
  26979. Object.defineProperty(BaseTexture.prototype, "uid", {
  26980. get: function () {
  26981. if (!this._uid) {
  26982. this._uid = BABYLON.Tools.RandomId();
  26983. }
  26984. return this._uid;
  26985. },
  26986. enumerable: true,
  26987. configurable: true
  26988. });
  26989. BaseTexture.prototype.toString = function () {
  26990. return this.name;
  26991. };
  26992. BaseTexture.prototype.getClassName = function () {
  26993. return "BaseTexture";
  26994. };
  26995. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26996. set: function (callback) {
  26997. if (this._onDisposeObserver) {
  26998. this.onDisposeObservable.remove(this._onDisposeObserver);
  26999. }
  27000. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27001. },
  27002. enumerable: true,
  27003. configurable: true
  27004. });
  27005. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  27006. get: function () {
  27007. return true;
  27008. },
  27009. enumerable: true,
  27010. configurable: true
  27011. });
  27012. BaseTexture.prototype.getScene = function () {
  27013. return this._scene;
  27014. };
  27015. BaseTexture.prototype.getTextureMatrix = function () {
  27016. return BABYLON.Matrix.IdentityReadOnly;
  27017. };
  27018. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27019. return BABYLON.Matrix.IdentityReadOnly;
  27020. };
  27021. BaseTexture.prototype.getInternalTexture = function () {
  27022. return this._texture;
  27023. };
  27024. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  27025. return !this.isBlocking || this.isReady();
  27026. };
  27027. BaseTexture.prototype.isReady = function () {
  27028. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27029. this.delayLoad();
  27030. return false;
  27031. }
  27032. if (this._texture) {
  27033. return this._texture.isReady;
  27034. }
  27035. return false;
  27036. };
  27037. BaseTexture.prototype.getSize = function () {
  27038. if (this._texture && this._texture.width) {
  27039. return new BABYLON.Size(this._texture.width, this._texture.height);
  27040. }
  27041. if (this._texture && this._texture._size) {
  27042. return new BABYLON.Size(this._texture._size, this._texture._size);
  27043. }
  27044. return BABYLON.Size.Zero();
  27045. };
  27046. BaseTexture.prototype.getBaseSize = function () {
  27047. if (!this.isReady() || !this._texture)
  27048. return BABYLON.Size.Zero();
  27049. if (this._texture._size) {
  27050. return new BABYLON.Size(this._texture._size, this._texture._size);
  27051. }
  27052. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27053. };
  27054. BaseTexture.prototype.scale = function (ratio) {
  27055. };
  27056. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27057. get: function () {
  27058. return false;
  27059. },
  27060. enumerable: true,
  27061. configurable: true
  27062. });
  27063. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27064. if (!this._scene) {
  27065. return null;
  27066. }
  27067. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27068. for (var index = 0; index < texturesCache.length; index++) {
  27069. var texturesCacheEntry = texturesCache[index];
  27070. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27071. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27072. texturesCacheEntry.incrementReferences();
  27073. return texturesCacheEntry;
  27074. }
  27075. }
  27076. }
  27077. return null;
  27078. };
  27079. BaseTexture.prototype._rebuild = function () {
  27080. };
  27081. BaseTexture.prototype.delayLoad = function () {
  27082. };
  27083. BaseTexture.prototype.clone = function () {
  27084. return null;
  27085. };
  27086. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27087. get: function () {
  27088. if (!this._texture) {
  27089. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27090. }
  27091. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27092. },
  27093. enumerable: true,
  27094. configurable: true
  27095. });
  27096. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27097. get: function () {
  27098. if (!this._texture) {
  27099. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27100. }
  27101. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27102. },
  27103. enumerable: true,
  27104. configurable: true
  27105. });
  27106. BaseTexture.prototype.readPixels = function (faceIndex) {
  27107. if (faceIndex === void 0) { faceIndex = 0; }
  27108. if (!this._texture) {
  27109. return null;
  27110. }
  27111. var size = this.getSize();
  27112. var scene = this.getScene();
  27113. if (!scene) {
  27114. return null;
  27115. }
  27116. var engine = scene.getEngine();
  27117. if (this._texture.isCube) {
  27118. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27119. }
  27120. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27121. };
  27122. BaseTexture.prototype.releaseInternalTexture = function () {
  27123. if (this._texture) {
  27124. this._texture.dispose();
  27125. this._texture = null;
  27126. }
  27127. };
  27128. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27129. get: function () {
  27130. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27131. return null;
  27132. }
  27133. if (!this._texture._sphericalPolynomial) {
  27134. this._texture._sphericalPolynomial =
  27135. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27136. }
  27137. return this._texture._sphericalPolynomial;
  27138. },
  27139. set: function (value) {
  27140. if (this._texture) {
  27141. this._texture._sphericalPolynomial = value;
  27142. }
  27143. },
  27144. enumerable: true,
  27145. configurable: true
  27146. });
  27147. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27148. get: function () {
  27149. if (this._texture) {
  27150. return this._texture._lodTextureHigh;
  27151. }
  27152. return null;
  27153. },
  27154. enumerable: true,
  27155. configurable: true
  27156. });
  27157. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27158. get: function () {
  27159. if (this._texture) {
  27160. return this._texture._lodTextureMid;
  27161. }
  27162. return null;
  27163. },
  27164. enumerable: true,
  27165. configurable: true
  27166. });
  27167. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27168. get: function () {
  27169. if (this._texture) {
  27170. return this._texture._lodTextureLow;
  27171. }
  27172. return null;
  27173. },
  27174. enumerable: true,
  27175. configurable: true
  27176. });
  27177. BaseTexture.prototype.dispose = function () {
  27178. if (!this._scene) {
  27179. return;
  27180. }
  27181. // Animations
  27182. this._scene.stopAnimation(this);
  27183. // Remove from scene
  27184. this._scene._removePendingData(this);
  27185. var index = this._scene.textures.indexOf(this);
  27186. if (index >= 0) {
  27187. this._scene.textures.splice(index, 1);
  27188. }
  27189. if (this._texture === undefined) {
  27190. return;
  27191. }
  27192. // Release
  27193. this.releaseInternalTexture();
  27194. // Callback
  27195. this.onDisposeObservable.notifyObservers(this);
  27196. this.onDisposeObservable.clear();
  27197. };
  27198. BaseTexture.prototype.serialize = function () {
  27199. if (!this.name) {
  27200. return null;
  27201. }
  27202. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27203. // Animations
  27204. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27205. return serializationObject;
  27206. };
  27207. BaseTexture.WhenAllReady = function (textures, callback) {
  27208. var numRemaining = textures.length;
  27209. if (numRemaining === 0) {
  27210. callback();
  27211. return;
  27212. }
  27213. var _loop_1 = function () {
  27214. texture = textures[i];
  27215. if (texture.isReady()) {
  27216. if (--numRemaining === 0) {
  27217. callback();
  27218. }
  27219. }
  27220. else {
  27221. onLoadObservable = texture.onLoadObservable;
  27222. var onLoadCallback_1 = function () {
  27223. onLoadObservable.removeCallback(onLoadCallback_1);
  27224. if (--numRemaining === 0) {
  27225. callback();
  27226. }
  27227. };
  27228. onLoadObservable.add(onLoadCallback_1);
  27229. }
  27230. };
  27231. var texture, onLoadObservable;
  27232. for (var i = 0; i < textures.length; i++) {
  27233. _loop_1();
  27234. }
  27235. };
  27236. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27237. __decorate([
  27238. BABYLON.serialize()
  27239. ], BaseTexture.prototype, "name", void 0);
  27240. __decorate([
  27241. BABYLON.serialize("hasAlpha")
  27242. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27243. __decorate([
  27244. BABYLON.serialize()
  27245. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27246. __decorate([
  27247. BABYLON.serialize()
  27248. ], BaseTexture.prototype, "level", void 0);
  27249. __decorate([
  27250. BABYLON.serialize()
  27251. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27252. __decorate([
  27253. BABYLON.serialize("coordinatesMode")
  27254. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27255. __decorate([
  27256. BABYLON.serialize()
  27257. ], BaseTexture.prototype, "wrapU", void 0);
  27258. __decorate([
  27259. BABYLON.serialize()
  27260. ], BaseTexture.prototype, "wrapV", void 0);
  27261. __decorate([
  27262. BABYLON.serialize()
  27263. ], BaseTexture.prototype, "wrapR", void 0);
  27264. __decorate([
  27265. BABYLON.serialize()
  27266. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27267. __decorate([
  27268. BABYLON.serialize()
  27269. ], BaseTexture.prototype, "isCube", void 0);
  27270. __decorate([
  27271. BABYLON.serialize()
  27272. ], BaseTexture.prototype, "is3D", void 0);
  27273. __decorate([
  27274. BABYLON.serialize()
  27275. ], BaseTexture.prototype, "gammaSpace", void 0);
  27276. __decorate([
  27277. BABYLON.serialize()
  27278. ], BaseTexture.prototype, "invertZ", void 0);
  27279. __decorate([
  27280. BABYLON.serialize()
  27281. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27282. __decorate([
  27283. BABYLON.serialize()
  27284. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27285. __decorate([
  27286. BABYLON.serialize()
  27287. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27288. __decorate([
  27289. BABYLON.serialize()
  27290. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27291. return BaseTexture;
  27292. }());
  27293. BABYLON.BaseTexture = BaseTexture;
  27294. })(BABYLON || (BABYLON = {}));
  27295. //# sourceMappingURL=babylon.baseTexture.js.map
  27296. "use strict";
  27297. var BABYLON;
  27298. (function (BABYLON) {
  27299. var Texture = /** @class */ (function (_super) {
  27300. __extends(Texture, _super);
  27301. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27302. if (noMipmap === void 0) { noMipmap = false; }
  27303. if (invertY === void 0) { invertY = true; }
  27304. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27305. if (onLoad === void 0) { onLoad = null; }
  27306. if (onError === void 0) { onError = null; }
  27307. if (buffer === void 0) { buffer = null; }
  27308. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27309. var _this = _super.call(this, scene) || this;
  27310. _this.uOffset = 0;
  27311. _this.vOffset = 0;
  27312. _this.uScale = 1.0;
  27313. _this.vScale = 1.0;
  27314. _this.uAng = 0;
  27315. _this.vAng = 0;
  27316. _this.wAng = 0;
  27317. _this._isBlocking = true;
  27318. _this.name = url || "";
  27319. _this.url = url;
  27320. _this._noMipmap = noMipmap;
  27321. _this._invertY = invertY;
  27322. _this._samplingMode = samplingMode;
  27323. _this._buffer = buffer;
  27324. _this._deleteBuffer = deleteBuffer;
  27325. if (format) {
  27326. _this._format = format;
  27327. }
  27328. scene = _this.getScene();
  27329. if (!scene) {
  27330. return _this;
  27331. }
  27332. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27333. var load = function () {
  27334. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27335. _this.onLoadObservable.notifyObservers(_this);
  27336. }
  27337. if (onLoad) {
  27338. onLoad();
  27339. }
  27340. if (!_this.isBlocking && scene) {
  27341. scene.resetCachedMaterial();
  27342. }
  27343. };
  27344. if (!_this.url) {
  27345. _this._delayedOnLoad = load;
  27346. _this._delayedOnError = onError;
  27347. return _this;
  27348. }
  27349. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27350. if (!_this._texture) {
  27351. if (!scene.useDelayedTextureLoading) {
  27352. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27353. if (deleteBuffer) {
  27354. delete _this._buffer;
  27355. }
  27356. }
  27357. else {
  27358. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27359. _this._delayedOnLoad = load;
  27360. _this._delayedOnError = onError;
  27361. }
  27362. }
  27363. else {
  27364. if (_this._texture.isReady) {
  27365. BABYLON.Tools.SetImmediate(function () { return load(); });
  27366. }
  27367. else {
  27368. _this._texture.onLoadedObservable.add(load);
  27369. }
  27370. }
  27371. return _this;
  27372. }
  27373. Object.defineProperty(Texture.prototype, "noMipmap", {
  27374. get: function () {
  27375. return this._noMipmap;
  27376. },
  27377. enumerable: true,
  27378. configurable: true
  27379. });
  27380. Object.defineProperty(Texture.prototype, "isBlocking", {
  27381. get: function () {
  27382. return this._isBlocking;
  27383. },
  27384. set: function (value) {
  27385. this._isBlocking = value;
  27386. },
  27387. enumerable: true,
  27388. configurable: true
  27389. });
  27390. Object.defineProperty(Texture.prototype, "samplingMode", {
  27391. get: function () {
  27392. return this._samplingMode;
  27393. },
  27394. enumerable: true,
  27395. configurable: true
  27396. });
  27397. Texture.prototype.updateURL = function (url) {
  27398. this.url = url;
  27399. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27400. this.delayLoad();
  27401. };
  27402. Texture.prototype.delayLoad = function () {
  27403. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27404. return;
  27405. }
  27406. var scene = this.getScene();
  27407. if (!scene) {
  27408. return;
  27409. }
  27410. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27411. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27412. if (!this._texture) {
  27413. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27414. if (this._deleteBuffer) {
  27415. delete this._buffer;
  27416. }
  27417. }
  27418. else {
  27419. if (this._delayedOnLoad) {
  27420. if (this._texture.isReady) {
  27421. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27422. }
  27423. else {
  27424. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27425. }
  27426. }
  27427. }
  27428. this._delayedOnLoad = null;
  27429. this._delayedOnError = null;
  27430. };
  27431. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27432. if (!this._texture) {
  27433. return;
  27434. }
  27435. var scene = this.getScene();
  27436. if (!scene) {
  27437. return;
  27438. }
  27439. this._samplingMode = samplingMode;
  27440. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27441. };
  27442. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27443. x *= this.uScale;
  27444. y *= this.vScale;
  27445. x -= 0.5 * this.uScale;
  27446. y -= 0.5 * this.vScale;
  27447. z -= 0.5;
  27448. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27449. t.x += 0.5 * this.uScale + this.uOffset;
  27450. t.y += 0.5 * this.vScale + this.vOffset;
  27451. t.z += 0.5;
  27452. };
  27453. Texture.prototype.getTextureMatrix = function () {
  27454. var _this = this;
  27455. if (this.uOffset === this._cachedUOffset &&
  27456. this.vOffset === this._cachedVOffset &&
  27457. this.uScale === this._cachedUScale &&
  27458. this.vScale === this._cachedVScale &&
  27459. this.uAng === this._cachedUAng &&
  27460. this.vAng === this._cachedVAng &&
  27461. this.wAng === this._cachedWAng) {
  27462. return this._cachedTextureMatrix;
  27463. }
  27464. this._cachedUOffset = this.uOffset;
  27465. this._cachedVOffset = this.vOffset;
  27466. this._cachedUScale = this.uScale;
  27467. this._cachedVScale = this.vScale;
  27468. this._cachedUAng = this.uAng;
  27469. this._cachedVAng = this.vAng;
  27470. this._cachedWAng = this.wAng;
  27471. if (!this._cachedTextureMatrix) {
  27472. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27473. this._rowGenerationMatrix = new BABYLON.Matrix();
  27474. this._t0 = BABYLON.Vector3.Zero();
  27475. this._t1 = BABYLON.Vector3.Zero();
  27476. this._t2 = BABYLON.Vector3.Zero();
  27477. }
  27478. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27479. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27480. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27481. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27482. this._t1.subtractInPlace(this._t0);
  27483. this._t2.subtractInPlace(this._t0);
  27484. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27485. this._cachedTextureMatrix.m[0] = this._t1.x;
  27486. this._cachedTextureMatrix.m[1] = this._t1.y;
  27487. this._cachedTextureMatrix.m[2] = this._t1.z;
  27488. this._cachedTextureMatrix.m[4] = this._t2.x;
  27489. this._cachedTextureMatrix.m[5] = this._t2.y;
  27490. this._cachedTextureMatrix.m[6] = this._t2.z;
  27491. this._cachedTextureMatrix.m[8] = this._t0.x;
  27492. this._cachedTextureMatrix.m[9] = this._t0.y;
  27493. this._cachedTextureMatrix.m[10] = this._t0.z;
  27494. var scene = this.getScene();
  27495. if (!scene) {
  27496. return this._cachedTextureMatrix;
  27497. }
  27498. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27499. return mat.hasTexture(_this);
  27500. });
  27501. return this._cachedTextureMatrix;
  27502. };
  27503. Texture.prototype.getReflectionTextureMatrix = function () {
  27504. var _this = this;
  27505. var scene = this.getScene();
  27506. if (!scene) {
  27507. return this._cachedTextureMatrix;
  27508. }
  27509. if (this.uOffset === this._cachedUOffset &&
  27510. this.vOffset === this._cachedVOffset &&
  27511. this.uScale === this._cachedUScale &&
  27512. this.vScale === this._cachedVScale &&
  27513. this.coordinatesMode === this._cachedCoordinatesMode) {
  27514. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27515. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27516. return this._cachedTextureMatrix;
  27517. }
  27518. }
  27519. else {
  27520. return this._cachedTextureMatrix;
  27521. }
  27522. }
  27523. if (!this._cachedTextureMatrix) {
  27524. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27525. }
  27526. if (!this._projectionModeMatrix) {
  27527. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27528. }
  27529. this._cachedUOffset = this.uOffset;
  27530. this._cachedVOffset = this.vOffset;
  27531. this._cachedUScale = this.uScale;
  27532. this._cachedVScale = this.vScale;
  27533. this._cachedCoordinatesMode = this.coordinatesMode;
  27534. switch (this.coordinatesMode) {
  27535. case Texture.PLANAR_MODE:
  27536. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27537. this._cachedTextureMatrix[0] = this.uScale;
  27538. this._cachedTextureMatrix[5] = this.vScale;
  27539. this._cachedTextureMatrix[12] = this.uOffset;
  27540. this._cachedTextureMatrix[13] = this.vOffset;
  27541. break;
  27542. case Texture.PROJECTION_MODE:
  27543. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27544. this._projectionModeMatrix.m[0] = 0.5;
  27545. this._projectionModeMatrix.m[5] = -0.5;
  27546. this._projectionModeMatrix.m[10] = 0.0;
  27547. this._projectionModeMatrix.m[12] = 0.5;
  27548. this._projectionModeMatrix.m[13] = 0.5;
  27549. this._projectionModeMatrix.m[14] = 1.0;
  27550. this._projectionModeMatrix.m[15] = 1.0;
  27551. var projectionMatrix = scene.getProjectionMatrix();
  27552. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27553. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27554. break;
  27555. default:
  27556. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27557. break;
  27558. }
  27559. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27560. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27561. });
  27562. return this._cachedTextureMatrix;
  27563. };
  27564. Texture.prototype.clone = function () {
  27565. var _this = this;
  27566. return BABYLON.SerializationHelper.Clone(function () {
  27567. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27568. }, this);
  27569. };
  27570. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27571. get: function () {
  27572. if (!this._onLoadObservable) {
  27573. this._onLoadObservable = new BABYLON.Observable();
  27574. }
  27575. return this._onLoadObservable;
  27576. },
  27577. enumerable: true,
  27578. configurable: true
  27579. });
  27580. Texture.prototype.serialize = function () {
  27581. var serializationObject = _super.prototype.serialize.call(this);
  27582. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27583. serializationObject.base64String = this._buffer;
  27584. serializationObject.name = serializationObject.name.replace("data:", "");
  27585. }
  27586. return serializationObject;
  27587. };
  27588. Texture.prototype.getClassName = function () {
  27589. return "Texture";
  27590. };
  27591. Texture.prototype.dispose = function () {
  27592. _super.prototype.dispose.call(this);
  27593. if (this.onLoadObservable) {
  27594. this.onLoadObservable.clear();
  27595. this._onLoadObservable = null;
  27596. }
  27597. this._delayedOnLoad = null;
  27598. this._delayedOnError = null;
  27599. };
  27600. // Statics
  27601. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27602. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27603. if (onLoad === void 0) { onLoad = null; }
  27604. if (onError === void 0) { onError = null; }
  27605. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27606. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27607. };
  27608. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27609. if (parsedTexture.customType) {
  27610. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27611. // Update Sampling Mode
  27612. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27613. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27614. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27615. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27616. }
  27617. }
  27618. return parsedCustomTexture;
  27619. }
  27620. if (parsedTexture.isCube) {
  27621. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27622. }
  27623. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27624. return null;
  27625. }
  27626. var texture = BABYLON.SerializationHelper.Parse(function () {
  27627. var generateMipMaps = true;
  27628. if (parsedTexture.noMipmap) {
  27629. generateMipMaps = false;
  27630. }
  27631. if (parsedTexture.mirrorPlane) {
  27632. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27633. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27634. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27635. return mirrorTexture;
  27636. }
  27637. else if (parsedTexture.isRenderTarget) {
  27638. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27639. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27640. return renderTargetTexture;
  27641. }
  27642. else {
  27643. var texture;
  27644. if (parsedTexture.base64String) {
  27645. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27646. }
  27647. else {
  27648. var url = rootUrl + parsedTexture.name;
  27649. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27650. url = parsedTexture.url;
  27651. }
  27652. texture = new Texture(url, scene, !generateMipMaps);
  27653. }
  27654. return texture;
  27655. }
  27656. }, parsedTexture, scene);
  27657. // Update Sampling Mode
  27658. if (parsedTexture.samplingMode) {
  27659. var sampling = parsedTexture.samplingMode;
  27660. if (texture._samplingMode !== sampling) {
  27661. texture.updateSamplingMode(sampling);
  27662. }
  27663. }
  27664. // Animations
  27665. if (parsedTexture.animations) {
  27666. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27667. var parsedAnimation = parsedTexture.animations[animationIndex];
  27668. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27669. }
  27670. }
  27671. return texture;
  27672. };
  27673. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27674. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27675. if (noMipmap === void 0) { noMipmap = false; }
  27676. if (invertY === void 0) { invertY = true; }
  27677. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27678. if (onLoad === void 0) { onLoad = null; }
  27679. if (onError === void 0) { onError = null; }
  27680. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27681. if (name.substr(0, 5) !== "data:") {
  27682. name = "data:" + name;
  27683. }
  27684. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27685. };
  27686. // Constants
  27687. Texture.NEAREST_SAMPLINGMODE = 1;
  27688. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27689. Texture.BILINEAR_SAMPLINGMODE = 2;
  27690. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27691. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27692. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27693. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27694. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27695. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27696. Texture.NEAREST_LINEAR = 7;
  27697. Texture.NEAREST_NEAREST = 8;
  27698. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27699. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27700. Texture.LINEAR_LINEAR = 11;
  27701. Texture.LINEAR_NEAREST = 12;
  27702. Texture.EXPLICIT_MODE = 0;
  27703. Texture.SPHERICAL_MODE = 1;
  27704. Texture.PLANAR_MODE = 2;
  27705. Texture.CUBIC_MODE = 3;
  27706. Texture.PROJECTION_MODE = 4;
  27707. Texture.SKYBOX_MODE = 5;
  27708. Texture.INVCUBIC_MODE = 6;
  27709. Texture.EQUIRECTANGULAR_MODE = 7;
  27710. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27711. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27712. Texture.CLAMP_ADDRESSMODE = 0;
  27713. Texture.WRAP_ADDRESSMODE = 1;
  27714. Texture.MIRROR_ADDRESSMODE = 2;
  27715. /**
  27716. * 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
  27717. */
  27718. Texture.UseSerializedUrlIfAny = false;
  27719. __decorate([
  27720. BABYLON.serialize()
  27721. ], Texture.prototype, "url", void 0);
  27722. __decorate([
  27723. BABYLON.serialize()
  27724. ], Texture.prototype, "uOffset", void 0);
  27725. __decorate([
  27726. BABYLON.serialize()
  27727. ], Texture.prototype, "vOffset", void 0);
  27728. __decorate([
  27729. BABYLON.serialize()
  27730. ], Texture.prototype, "uScale", void 0);
  27731. __decorate([
  27732. BABYLON.serialize()
  27733. ], Texture.prototype, "vScale", void 0);
  27734. __decorate([
  27735. BABYLON.serialize()
  27736. ], Texture.prototype, "uAng", void 0);
  27737. __decorate([
  27738. BABYLON.serialize()
  27739. ], Texture.prototype, "vAng", void 0);
  27740. __decorate([
  27741. BABYLON.serialize()
  27742. ], Texture.prototype, "wAng", void 0);
  27743. __decorate([
  27744. BABYLON.serialize()
  27745. ], Texture.prototype, "isBlocking", null);
  27746. return Texture;
  27747. }(BABYLON.BaseTexture));
  27748. BABYLON.Texture = Texture;
  27749. })(BABYLON || (BABYLON = {}));
  27750. //# sourceMappingURL=babylon.texture.js.map
  27751. "use strict";
  27752. var BABYLON;
  27753. (function (BABYLON) {
  27754. var _InstancesBatch = /** @class */ (function () {
  27755. function _InstancesBatch() {
  27756. this.mustReturn = false;
  27757. this.visibleInstances = new Array();
  27758. this.renderSelf = new Array();
  27759. }
  27760. return _InstancesBatch;
  27761. }());
  27762. BABYLON._InstancesBatch = _InstancesBatch;
  27763. var Mesh = /** @class */ (function (_super) {
  27764. __extends(Mesh, _super);
  27765. /**
  27766. * @constructor
  27767. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27768. * @param {Scene} scene The scene to add this mesh to.
  27769. * @param {Node} parent The parent of this mesh, if it has one
  27770. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27771. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27772. * When false, achieved by calling a clone(), also passing False.
  27773. * This will make creation of children, recursive.
  27774. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27775. */
  27776. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27777. if (scene === void 0) { scene = null; }
  27778. if (parent === void 0) { parent = null; }
  27779. if (source === void 0) { source = null; }
  27780. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27781. var _this = _super.call(this, name, scene) || this;
  27782. // Events
  27783. /**
  27784. * An event triggered before rendering the mesh
  27785. * @type {BABYLON.Observable}
  27786. */
  27787. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27788. /**
  27789. * An event triggered after rendering the mesh
  27790. * @type {BABYLON.Observable}
  27791. */
  27792. _this.onAfterRenderObservable = new BABYLON.Observable();
  27793. /**
  27794. * An event triggered before drawing the mesh
  27795. * @type {BABYLON.Observable}
  27796. */
  27797. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27798. // Members
  27799. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27800. _this.instances = new Array();
  27801. _this._LODLevels = new Array();
  27802. _this._visibleInstances = {};
  27803. _this._renderIdForInstances = new Array();
  27804. _this._batchCache = new _InstancesBatch();
  27805. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27806. // Use by builder only to know what orientation were the mesh build in.
  27807. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27808. _this.overrideMaterialSideOrientation = null;
  27809. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27810. // Will be used to save a source mesh reference, If any
  27811. _this._source = null;
  27812. scene = _this.getScene();
  27813. if (source) {
  27814. // Source mesh
  27815. _this._source = source;
  27816. // Geometry
  27817. if (source._geometry) {
  27818. source._geometry.applyToMesh(_this);
  27819. }
  27820. // Deep copy
  27821. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  27822. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  27823. // Metadata
  27824. if (source.metadata && source.metadata.clone) {
  27825. _this.metadata = source.metadata.clone();
  27826. }
  27827. else {
  27828. _this.metadata = source.metadata;
  27829. }
  27830. // Tags
  27831. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27832. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27833. }
  27834. // Parent
  27835. _this.parent = source.parent;
  27836. // Pivot
  27837. _this.setPivotMatrix(source.getPivotMatrix());
  27838. _this.id = name + "." + source.id;
  27839. // Material
  27840. _this.material = source.material;
  27841. var index;
  27842. if (!doNotCloneChildren) {
  27843. // Children
  27844. var directDescendants = source.getDescendants(true);
  27845. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27846. var child = directDescendants[index_1];
  27847. if (child.clone) {
  27848. child.clone(name + "." + child.name, _this);
  27849. }
  27850. }
  27851. }
  27852. // Physics clone
  27853. var physicsEngine = _this.getScene().getPhysicsEngine();
  27854. if (clonePhysicsImpostor && physicsEngine) {
  27855. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27856. if (impostor) {
  27857. _this.physicsImpostor = impostor.clone(_this);
  27858. }
  27859. }
  27860. // Particles
  27861. for (index = 0; index < scene.particleSystems.length; index++) {
  27862. var system = scene.particleSystems[index];
  27863. if (system.emitter === source) {
  27864. system.clone(system.name, _this);
  27865. }
  27866. }
  27867. _this.computeWorldMatrix(true);
  27868. }
  27869. // Parent
  27870. if (parent !== null) {
  27871. _this.parent = parent;
  27872. }
  27873. return _this;
  27874. }
  27875. Object.defineProperty(Mesh, "FRONTSIDE", {
  27876. /**
  27877. * Mesh side orientation : usually the external or front surface
  27878. */
  27879. get: function () {
  27880. return Mesh._FRONTSIDE;
  27881. },
  27882. enumerable: true,
  27883. configurable: true
  27884. });
  27885. Object.defineProperty(Mesh, "BACKSIDE", {
  27886. /**
  27887. * Mesh side orientation : usually the internal or back surface
  27888. */
  27889. get: function () {
  27890. return Mesh._BACKSIDE;
  27891. },
  27892. enumerable: true,
  27893. configurable: true
  27894. });
  27895. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27896. /**
  27897. * Mesh side orientation : both internal and external or front and back surfaces
  27898. */
  27899. get: function () {
  27900. return Mesh._DOUBLESIDE;
  27901. },
  27902. enumerable: true,
  27903. configurable: true
  27904. });
  27905. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27906. /**
  27907. * Mesh side orientation : by default, `FRONTSIDE`
  27908. */
  27909. get: function () {
  27910. return Mesh._DEFAULTSIDE;
  27911. },
  27912. enumerable: true,
  27913. configurable: true
  27914. });
  27915. Object.defineProperty(Mesh, "NO_CAP", {
  27916. /**
  27917. * Mesh cap setting : no cap
  27918. */
  27919. get: function () {
  27920. return Mesh._NO_CAP;
  27921. },
  27922. enumerable: true,
  27923. configurable: true
  27924. });
  27925. Object.defineProperty(Mesh, "CAP_START", {
  27926. /**
  27927. * Mesh cap setting : one cap at the beginning of the mesh
  27928. */
  27929. get: function () {
  27930. return Mesh._CAP_START;
  27931. },
  27932. enumerable: true,
  27933. configurable: true
  27934. });
  27935. Object.defineProperty(Mesh, "CAP_END", {
  27936. /**
  27937. * Mesh cap setting : one cap at the end of the mesh
  27938. */
  27939. get: function () {
  27940. return Mesh._CAP_END;
  27941. },
  27942. enumerable: true,
  27943. configurable: true
  27944. });
  27945. Object.defineProperty(Mesh, "CAP_ALL", {
  27946. /**
  27947. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27948. */
  27949. get: function () {
  27950. return Mesh._CAP_ALL;
  27951. },
  27952. enumerable: true,
  27953. configurable: true
  27954. });
  27955. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27956. set: function (callback) {
  27957. if (this._onBeforeDrawObserver) {
  27958. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27959. }
  27960. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27961. },
  27962. enumerable: true,
  27963. configurable: true
  27964. });
  27965. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27966. get: function () {
  27967. return this._morphTargetManager;
  27968. },
  27969. set: function (value) {
  27970. if (this._morphTargetManager === value) {
  27971. return;
  27972. }
  27973. this._morphTargetManager = value;
  27974. this._syncGeometryWithMorphTargetManager();
  27975. },
  27976. enumerable: true,
  27977. configurable: true
  27978. });
  27979. Object.defineProperty(Mesh.prototype, "source", {
  27980. get: function () {
  27981. return this._source;
  27982. },
  27983. enumerable: true,
  27984. configurable: true
  27985. });
  27986. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27987. get: function () {
  27988. return this._unIndexed;
  27989. },
  27990. set: function (value) {
  27991. if (this._unIndexed !== value) {
  27992. this._unIndexed = value;
  27993. this._markSubMeshesAsAttributesDirty();
  27994. }
  27995. },
  27996. enumerable: true,
  27997. configurable: true
  27998. });
  27999. // Methods
  28000. /**
  28001. * Returns the string "Mesh".
  28002. */
  28003. Mesh.prototype.getClassName = function () {
  28004. return "Mesh";
  28005. };
  28006. /**
  28007. * Returns a string.
  28008. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28009. */
  28010. Mesh.prototype.toString = function (fullDetails) {
  28011. var ret = _super.prototype.toString.call(this, fullDetails);
  28012. ret += ", n vertices: " + this.getTotalVertices();
  28013. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  28014. if (this.animations) {
  28015. for (var i = 0; i < this.animations.length; i++) {
  28016. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  28017. }
  28018. }
  28019. if (fullDetails) {
  28020. if (this._geometry) {
  28021. var ib = this.getIndices();
  28022. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28023. if (vb && ib) {
  28024. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  28025. }
  28026. }
  28027. else {
  28028. ret += ", flat shading: UNKNOWN";
  28029. }
  28030. }
  28031. return ret;
  28032. };
  28033. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  28034. /**
  28035. * True if the mesh has some Levels Of Details (LOD).
  28036. * Returns a boolean.
  28037. */
  28038. get: function () {
  28039. return this._LODLevels.length > 0;
  28040. },
  28041. enumerable: true,
  28042. configurable: true
  28043. });
  28044. /**
  28045. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28046. * @returns an array of {BABYLON.MeshLODLevel}
  28047. */
  28048. Mesh.prototype.getLODLevels = function () {
  28049. return this._LODLevels;
  28050. };
  28051. Mesh.prototype._sortLODLevels = function () {
  28052. this._LODLevels.sort(function (a, b) {
  28053. if (a.distance < b.distance) {
  28054. return 1;
  28055. }
  28056. if (a.distance > b.distance) {
  28057. return -1;
  28058. }
  28059. return 0;
  28060. });
  28061. };
  28062. /**
  28063. * Add a mesh as LOD level triggered at the given distance.
  28064. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28065. * @param {number} distance The distance from the center of the object to show this level
  28066. * @param {Mesh} mesh The mesh to be added as LOD level
  28067. * @return {Mesh} This mesh (for chaining)
  28068. */
  28069. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28070. if (mesh && mesh._masterMesh) {
  28071. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28072. return this;
  28073. }
  28074. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28075. this._LODLevels.push(level);
  28076. if (mesh) {
  28077. mesh._masterMesh = this;
  28078. }
  28079. this._sortLODLevels();
  28080. return this;
  28081. };
  28082. /**
  28083. * Returns the LOD level mesh at the passed distance or null if not found.
  28084. * It is related to the method `addLODLevel(distance, mesh)`.
  28085. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28086. * Returns an object Mesh or `null`.
  28087. */
  28088. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28089. for (var index = 0; index < this._LODLevels.length; index++) {
  28090. var level = this._LODLevels[index];
  28091. if (level.distance === distance) {
  28092. return level.mesh;
  28093. }
  28094. }
  28095. return null;
  28096. };
  28097. /**
  28098. * Remove a mesh from the LOD array
  28099. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28100. * @param {Mesh} mesh The mesh to be removed.
  28101. * @return {Mesh} This mesh (for chaining)
  28102. */
  28103. Mesh.prototype.removeLODLevel = function (mesh) {
  28104. for (var index = 0; index < this._LODLevels.length; index++) {
  28105. if (this._LODLevels[index].mesh === mesh) {
  28106. this._LODLevels.splice(index, 1);
  28107. if (mesh) {
  28108. mesh._masterMesh = null;
  28109. }
  28110. }
  28111. }
  28112. this._sortLODLevels();
  28113. return this;
  28114. };
  28115. /**
  28116. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28117. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28118. */
  28119. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28120. if (!this._LODLevels || this._LODLevels.length === 0) {
  28121. return this;
  28122. }
  28123. var bSphere;
  28124. if (boundingSphere) {
  28125. bSphere = boundingSphere;
  28126. }
  28127. else {
  28128. var boundingInfo = this.getBoundingInfo();
  28129. bSphere = boundingInfo.boundingSphere;
  28130. }
  28131. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28132. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28133. if (this.onLODLevelSelection) {
  28134. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28135. }
  28136. return this;
  28137. }
  28138. for (var index = 0; index < this._LODLevels.length; index++) {
  28139. var level = this._LODLevels[index];
  28140. if (level.distance < distanceToCamera) {
  28141. if (level.mesh) {
  28142. level.mesh._preActivate();
  28143. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28144. }
  28145. if (this.onLODLevelSelection) {
  28146. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28147. }
  28148. return level.mesh;
  28149. }
  28150. }
  28151. if (this.onLODLevelSelection) {
  28152. this.onLODLevelSelection(distanceToCamera, this, this);
  28153. }
  28154. return this;
  28155. };
  28156. Object.defineProperty(Mesh.prototype, "geometry", {
  28157. /**
  28158. * Returns the mesh internal Geometry object.
  28159. */
  28160. get: function () {
  28161. return this._geometry;
  28162. },
  28163. enumerable: true,
  28164. configurable: true
  28165. });
  28166. /**
  28167. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28168. */
  28169. Mesh.prototype.getTotalVertices = function () {
  28170. if (this._geometry === null || this._geometry === undefined) {
  28171. return 0;
  28172. }
  28173. return this._geometry.getTotalVertices();
  28174. };
  28175. /**
  28176. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28177. * 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.
  28178. * You can force the copy with forceCopy === true
  28179. * Returns null if the mesh has no geometry or no vertex buffer.
  28180. * Possible `kind` values :
  28181. * - BABYLON.VertexBuffer.PositionKind
  28182. * - BABYLON.VertexBuffer.UVKind
  28183. * - BABYLON.VertexBuffer.UV2Kind
  28184. * - BABYLON.VertexBuffer.UV3Kind
  28185. * - BABYLON.VertexBuffer.UV4Kind
  28186. * - BABYLON.VertexBuffer.UV5Kind
  28187. * - BABYLON.VertexBuffer.UV6Kind
  28188. * - BABYLON.VertexBuffer.ColorKind
  28189. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28190. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28191. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28192. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28193. */
  28194. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28195. if (!this._geometry) {
  28196. return null;
  28197. }
  28198. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28199. };
  28200. /**
  28201. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28202. * Returns `null` if the mesh has no geometry.
  28203. * Possible `kind` values :
  28204. * - BABYLON.VertexBuffer.PositionKind
  28205. * - BABYLON.VertexBuffer.UVKind
  28206. * - BABYLON.VertexBuffer.UV2Kind
  28207. * - BABYLON.VertexBuffer.UV3Kind
  28208. * - BABYLON.VertexBuffer.UV4Kind
  28209. * - BABYLON.VertexBuffer.UV5Kind
  28210. * - BABYLON.VertexBuffer.UV6Kind
  28211. * - BABYLON.VertexBuffer.ColorKind
  28212. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28213. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28214. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28215. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28216. */
  28217. Mesh.prototype.getVertexBuffer = function (kind) {
  28218. if (!this._geometry) {
  28219. return null;
  28220. }
  28221. return this._geometry.getVertexBuffer(kind);
  28222. };
  28223. /**
  28224. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28225. * Possible `kind` values :
  28226. * - BABYLON.VertexBuffer.PositionKind
  28227. * - BABYLON.VertexBuffer.UVKind
  28228. * - BABYLON.VertexBuffer.UV2Kind
  28229. * - BABYLON.VertexBuffer.UV3Kind
  28230. * - BABYLON.VertexBuffer.UV4Kind
  28231. * - BABYLON.VertexBuffer.UV5Kind
  28232. * - BABYLON.VertexBuffer.UV6Kind
  28233. * - BABYLON.VertexBuffer.ColorKind
  28234. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28235. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28236. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28237. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28238. */
  28239. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28240. if (!this._geometry) {
  28241. if (this._delayInfo) {
  28242. return this._delayInfo.indexOf(kind) !== -1;
  28243. }
  28244. return false;
  28245. }
  28246. return this._geometry.isVerticesDataPresent(kind);
  28247. };
  28248. /**
  28249. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28250. * Possible `kind` values :
  28251. * - BABYLON.VertexBuffer.PositionKind
  28252. * - BABYLON.VertexBuffer.UVKind
  28253. * - BABYLON.VertexBuffer.UV2Kind
  28254. * - BABYLON.VertexBuffer.UV3Kind
  28255. * - BABYLON.VertexBuffer.UV4Kind
  28256. * - BABYLON.VertexBuffer.UV5Kind
  28257. * - BABYLON.VertexBuffer.UV6Kind
  28258. * - BABYLON.VertexBuffer.ColorKind
  28259. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28260. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28261. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28262. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28263. */
  28264. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28265. if (!this._geometry) {
  28266. if (this._delayInfo) {
  28267. return this._delayInfo.indexOf(kind) !== -1;
  28268. }
  28269. return false;
  28270. }
  28271. return this._geometry.isVertexBufferUpdatable(kind);
  28272. };
  28273. /**
  28274. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28275. * Possible `kind` values :
  28276. * - BABYLON.VertexBuffer.PositionKind
  28277. * - BABYLON.VertexBuffer.UVKind
  28278. * - BABYLON.VertexBuffer.UV2Kind
  28279. * - BABYLON.VertexBuffer.UV3Kind
  28280. * - BABYLON.VertexBuffer.UV4Kind
  28281. * - BABYLON.VertexBuffer.UV5Kind
  28282. * - BABYLON.VertexBuffer.UV6Kind
  28283. * - BABYLON.VertexBuffer.ColorKind
  28284. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28285. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28286. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28287. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28288. */
  28289. Mesh.prototype.getVerticesDataKinds = function () {
  28290. if (!this._geometry) {
  28291. var result = new Array();
  28292. if (this._delayInfo) {
  28293. this._delayInfo.forEach(function (kind, index, array) {
  28294. result.push(kind);
  28295. });
  28296. }
  28297. return result;
  28298. }
  28299. return this._geometry.getVerticesDataKinds();
  28300. };
  28301. /**
  28302. * Returns a positive integer : the total number of indices in this mesh geometry.
  28303. * Returns zero if the mesh has no geometry.
  28304. */
  28305. Mesh.prototype.getTotalIndices = function () {
  28306. if (!this._geometry) {
  28307. return 0;
  28308. }
  28309. return this._geometry.getTotalIndices();
  28310. };
  28311. /**
  28312. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28313. * 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.
  28314. * Returns an empty array if the mesh has no geometry.
  28315. */
  28316. Mesh.prototype.getIndices = function (copyWhenShared) {
  28317. if (!this._geometry) {
  28318. return [];
  28319. }
  28320. return this._geometry.getIndices(copyWhenShared);
  28321. };
  28322. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28323. get: function () {
  28324. return this._masterMesh !== null && this._masterMesh !== undefined;
  28325. },
  28326. enumerable: true,
  28327. configurable: true
  28328. });
  28329. /**
  28330. * Determine if the current mesh is ready to be rendered
  28331. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28332. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28333. * @returns true if all associated assets are ready (material, textures, shaders)
  28334. */
  28335. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28336. if (completeCheck === void 0) { completeCheck = false; }
  28337. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28338. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28339. return false;
  28340. }
  28341. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28342. return false;
  28343. }
  28344. if (!this.subMeshes || this.subMeshes.length === 0) {
  28345. return true;
  28346. }
  28347. if (!completeCheck) {
  28348. return true;
  28349. }
  28350. var engine = this.getEngine();
  28351. var scene = this.getScene();
  28352. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28353. this.computeWorldMatrix();
  28354. var mat = this.material || scene.defaultMaterial;
  28355. if (mat) {
  28356. if (mat.storeEffectOnSubMeshes) {
  28357. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28358. var subMesh = _a[_i];
  28359. var effectiveMaterial = subMesh.getMaterial();
  28360. if (effectiveMaterial) {
  28361. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28362. return false;
  28363. }
  28364. }
  28365. }
  28366. }
  28367. else {
  28368. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28369. return false;
  28370. }
  28371. }
  28372. }
  28373. // Shadows
  28374. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28375. var light = _c[_b];
  28376. var generator = light.getShadowGenerator();
  28377. if (generator) {
  28378. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28379. var subMesh = _e[_d];
  28380. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28381. return false;
  28382. }
  28383. }
  28384. }
  28385. }
  28386. // LOD
  28387. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28388. var lod = _g[_f];
  28389. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28390. return false;
  28391. }
  28392. }
  28393. return true;
  28394. };
  28395. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28396. /**
  28397. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28398. * This property is pertinent only for updatable parametric shapes.
  28399. */
  28400. get: function () {
  28401. return this._areNormalsFrozen;
  28402. },
  28403. enumerable: true,
  28404. configurable: true
  28405. });
  28406. /**
  28407. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28408. * It has no effect at all on other shapes.
  28409. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28410. * Returns the Mesh.
  28411. */
  28412. Mesh.prototype.freezeNormals = function () {
  28413. this._areNormalsFrozen = true;
  28414. return this;
  28415. };
  28416. /**
  28417. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28418. * It has no effect at all on other shapes.
  28419. * It reactivates the mesh normals computation if it was previously frozen.
  28420. * Returns the Mesh.
  28421. */
  28422. Mesh.prototype.unfreezeNormals = function () {
  28423. this._areNormalsFrozen = false;
  28424. return this;
  28425. };
  28426. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28427. /**
  28428. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28429. */
  28430. set: function (count) {
  28431. this._overridenInstanceCount = count;
  28432. },
  28433. enumerable: true,
  28434. configurable: true
  28435. });
  28436. // Methods
  28437. Mesh.prototype._preActivate = function () {
  28438. var sceneRenderId = this.getScene().getRenderId();
  28439. if (this._preActivateId === sceneRenderId) {
  28440. return this;
  28441. }
  28442. this._preActivateId = sceneRenderId;
  28443. this._visibleInstances = null;
  28444. return this;
  28445. };
  28446. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28447. if (this._visibleInstances) {
  28448. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28449. }
  28450. return this;
  28451. };
  28452. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28453. if (!this._visibleInstances) {
  28454. this._visibleInstances = {};
  28455. this._visibleInstances.defaultRenderId = renderId;
  28456. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28457. }
  28458. if (!this._visibleInstances[renderId]) {
  28459. this._visibleInstances[renderId] = new Array();
  28460. }
  28461. this._visibleInstances[renderId].push(instance);
  28462. return this;
  28463. };
  28464. /**
  28465. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28466. * This means the mesh underlying bounding box and sphere are recomputed.
  28467. * Returns the Mesh.
  28468. */
  28469. Mesh.prototype.refreshBoundingInfo = function () {
  28470. return this._refreshBoundingInfo(false);
  28471. };
  28472. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28473. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28474. return this;
  28475. }
  28476. var data = this._getPositionData(applySkeleton);
  28477. if (data) {
  28478. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28479. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28480. }
  28481. if (this.subMeshes) {
  28482. for (var index = 0; index < this.subMeshes.length; index++) {
  28483. this.subMeshes[index].refreshBoundingInfo();
  28484. }
  28485. }
  28486. this._updateBoundingInfo();
  28487. return this;
  28488. };
  28489. Mesh.prototype._getPositionData = function (applySkeleton) {
  28490. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28491. if (data && applySkeleton && this.skeleton) {
  28492. data = BABYLON.Tools.Slice(data);
  28493. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28494. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28495. if (matricesWeightsData && matricesIndicesData) {
  28496. var needExtras = this.numBoneInfluencers > 4;
  28497. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28498. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28499. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28500. var tempVector = BABYLON.Tmp.Vector3[0];
  28501. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28502. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28503. var matWeightIdx = 0;
  28504. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28505. finalMatrix.reset();
  28506. var inf;
  28507. var weight;
  28508. for (inf = 0; inf < 4; inf++) {
  28509. weight = matricesWeightsData[matWeightIdx + inf];
  28510. if (weight <= 0)
  28511. break;
  28512. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28513. finalMatrix.addToSelf(tempMatrix);
  28514. }
  28515. if (needExtras) {
  28516. for (inf = 0; inf < 4; inf++) {
  28517. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28518. if (weight <= 0)
  28519. break;
  28520. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28521. finalMatrix.addToSelf(tempMatrix);
  28522. }
  28523. }
  28524. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28525. tempVector.toArray(data, index);
  28526. }
  28527. }
  28528. }
  28529. return data;
  28530. };
  28531. Mesh.prototype._createGlobalSubMesh = function (force) {
  28532. var totalVertices = this.getTotalVertices();
  28533. if (!totalVertices || !this.getIndices()) {
  28534. return null;
  28535. }
  28536. // Check if we need to recreate the submeshes
  28537. if (this.subMeshes && this.subMeshes.length > 0) {
  28538. var ib = this.getIndices();
  28539. if (!ib) {
  28540. return null;
  28541. }
  28542. var totalIndices = ib.length;
  28543. var needToRecreate = false;
  28544. if (force) {
  28545. needToRecreate = true;
  28546. }
  28547. else {
  28548. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28549. var submesh = _a[_i];
  28550. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28551. needToRecreate = true;
  28552. break;
  28553. }
  28554. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28555. needToRecreate = true;
  28556. break;
  28557. }
  28558. }
  28559. }
  28560. if (!needToRecreate) {
  28561. return this.subMeshes[0];
  28562. }
  28563. }
  28564. this.releaseSubMeshes();
  28565. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28566. };
  28567. Mesh.prototype.subdivide = function (count) {
  28568. if (count < 1) {
  28569. return;
  28570. }
  28571. var totalIndices = this.getTotalIndices();
  28572. var subdivisionSize = (totalIndices / count) | 0;
  28573. var offset = 0;
  28574. // Ensure that subdivisionSize is a multiple of 3
  28575. while (subdivisionSize % 3 !== 0) {
  28576. subdivisionSize++;
  28577. }
  28578. this.releaseSubMeshes();
  28579. for (var index = 0; index < count; index++) {
  28580. if (offset >= totalIndices) {
  28581. break;
  28582. }
  28583. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28584. offset += subdivisionSize;
  28585. }
  28586. this.synchronizeInstances();
  28587. };
  28588. /**
  28589. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28590. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28591. * The `data` are either a numeric array either a Float32Array.
  28592. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28593. * 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).
  28594. * Note that a new underlying VertexBuffer object is created each call.
  28595. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28596. *
  28597. * Possible `kind` values :
  28598. * - BABYLON.VertexBuffer.PositionKind
  28599. * - BABYLON.VertexBuffer.UVKind
  28600. * - BABYLON.VertexBuffer.UV2Kind
  28601. * - BABYLON.VertexBuffer.UV3Kind
  28602. * - BABYLON.VertexBuffer.UV4Kind
  28603. * - BABYLON.VertexBuffer.UV5Kind
  28604. * - BABYLON.VertexBuffer.UV6Kind
  28605. * - BABYLON.VertexBuffer.ColorKind
  28606. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28607. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28608. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28609. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28610. *
  28611. * Returns the Mesh.
  28612. */
  28613. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28614. if (updatable === void 0) { updatable = false; }
  28615. if (!this._geometry) {
  28616. var vertexData = new BABYLON.VertexData();
  28617. vertexData.set(data, kind);
  28618. var scene = this.getScene();
  28619. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28620. }
  28621. else {
  28622. this._geometry.setVerticesData(kind, data, updatable, stride);
  28623. }
  28624. return this;
  28625. };
  28626. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28627. if (updatable === void 0) { updatable = true; }
  28628. var vb = this.getVertexBuffer(kind);
  28629. if (!vb || vb.isUpdatable() === updatable) {
  28630. return;
  28631. }
  28632. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28633. };
  28634. /**
  28635. * Sets the mesh VertexBuffer.
  28636. * Returns the Mesh.
  28637. */
  28638. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28639. if (!this._geometry) {
  28640. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28641. }
  28642. this._geometry.setVerticesBuffer(buffer);
  28643. return this;
  28644. };
  28645. /**
  28646. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28647. * If the mesh has no geometry, it is simply returned as it is.
  28648. * The `data` are either a numeric array either a Float32Array.
  28649. * No new underlying VertexBuffer object is created.
  28650. * 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.
  28651. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28652. *
  28653. * Possible `kind` values :
  28654. * - BABYLON.VertexBuffer.PositionKind
  28655. * - BABYLON.VertexBuffer.UVKind
  28656. * - BABYLON.VertexBuffer.UV2Kind
  28657. * - BABYLON.VertexBuffer.UV3Kind
  28658. * - BABYLON.VertexBuffer.UV4Kind
  28659. * - BABYLON.VertexBuffer.UV5Kind
  28660. * - BABYLON.VertexBuffer.UV6Kind
  28661. * - BABYLON.VertexBuffer.ColorKind
  28662. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28663. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28664. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28665. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28666. *
  28667. * Returns the Mesh.
  28668. */
  28669. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28670. if (!this._geometry) {
  28671. return this;
  28672. }
  28673. if (!makeItUnique) {
  28674. this._geometry.updateVerticesData(kind, data, updateExtends);
  28675. }
  28676. else {
  28677. this.makeGeometryUnique();
  28678. this.updateVerticesData(kind, data, updateExtends, false);
  28679. }
  28680. return this;
  28681. };
  28682. /**
  28683. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28684. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28685. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28686. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28687. * Returns the Mesh.
  28688. */
  28689. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28690. if (computeNormals === void 0) { computeNormals = true; }
  28691. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28692. if (!positions) {
  28693. return this;
  28694. }
  28695. positionFunction(positions);
  28696. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28697. if (computeNormals) {
  28698. var indices = this.getIndices();
  28699. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28700. if (!normals) {
  28701. return this;
  28702. }
  28703. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28704. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28705. }
  28706. return this;
  28707. };
  28708. /**
  28709. * Creates a un-shared specific occurence of the geometry for the mesh.
  28710. * Returns the Mesh.
  28711. */
  28712. Mesh.prototype.makeGeometryUnique = function () {
  28713. if (!this._geometry) {
  28714. return this;
  28715. }
  28716. var oldGeometry = this._geometry;
  28717. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28718. oldGeometry.releaseForMesh(this, true);
  28719. geometry.applyToMesh(this);
  28720. return this;
  28721. };
  28722. /**
  28723. * Sets the mesh indices.
  28724. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28725. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28726. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28727. * This method creates a new index buffer each call.
  28728. * Returns the Mesh.
  28729. */
  28730. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28731. if (totalVertices === void 0) { totalVertices = null; }
  28732. if (updatable === void 0) { updatable = false; }
  28733. if (!this._geometry) {
  28734. var vertexData = new BABYLON.VertexData();
  28735. vertexData.indices = indices;
  28736. var scene = this.getScene();
  28737. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28738. }
  28739. else {
  28740. this._geometry.setIndices(indices, totalVertices, updatable);
  28741. }
  28742. return this;
  28743. };
  28744. /**
  28745. * Update the current index buffer
  28746. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28747. * Returns the Mesh.
  28748. */
  28749. Mesh.prototype.updateIndices = function (indices, offset) {
  28750. if (!this._geometry) {
  28751. return this;
  28752. }
  28753. this._geometry.updateIndices(indices, offset);
  28754. return this;
  28755. };
  28756. /**
  28757. * Invert the geometry to move from a right handed system to a left handed one.
  28758. * Returns the Mesh.
  28759. */
  28760. Mesh.prototype.toLeftHanded = function () {
  28761. if (!this._geometry) {
  28762. return this;
  28763. }
  28764. this._geometry.toLeftHanded();
  28765. return this;
  28766. };
  28767. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28768. if (!this._geometry) {
  28769. return this;
  28770. }
  28771. var engine = this.getScene().getEngine();
  28772. // Wireframe
  28773. var indexToBind;
  28774. if (this._unIndexed) {
  28775. indexToBind = null;
  28776. }
  28777. else {
  28778. switch (fillMode) {
  28779. case BABYLON.Material.PointFillMode:
  28780. indexToBind = null;
  28781. break;
  28782. case BABYLON.Material.WireFrameFillMode:
  28783. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28784. break;
  28785. default:
  28786. case BABYLON.Material.TriangleFillMode:
  28787. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28788. break;
  28789. }
  28790. }
  28791. // VBOs
  28792. this._geometry._bind(effect, indexToBind);
  28793. return this;
  28794. };
  28795. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28796. if (alternate === void 0) { alternate = false; }
  28797. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28798. return this;
  28799. }
  28800. this.onBeforeDrawObservable.notifyObservers(this);
  28801. var scene = this.getScene();
  28802. var engine = scene.getEngine();
  28803. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28804. // or triangles as points
  28805. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28806. }
  28807. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28808. // Triangles as wireframe
  28809. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28810. }
  28811. else {
  28812. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28813. }
  28814. if (scene._isAlternateRenderingEnabled && !alternate) {
  28815. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28816. if (!effect || !scene.activeCamera) {
  28817. return this;
  28818. }
  28819. scene._switchToAlternateCameraConfiguration(true);
  28820. this._effectiveMaterial.bindView(effect);
  28821. this._effectiveMaterial.bindViewProjection(effect);
  28822. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28823. this._draw(subMesh, fillMode, instancesCount, true);
  28824. engine.setViewport(scene.activeCamera.viewport);
  28825. scene._switchToAlternateCameraConfiguration(false);
  28826. this._effectiveMaterial.bindView(effect);
  28827. this._effectiveMaterial.bindViewProjection(effect);
  28828. }
  28829. return this;
  28830. };
  28831. /**
  28832. * Registers for this mesh a javascript function called just before the rendering process.
  28833. * This function is passed the current mesh.
  28834. * Return the Mesh.
  28835. */
  28836. Mesh.prototype.registerBeforeRender = function (func) {
  28837. this.onBeforeRenderObservable.add(func);
  28838. return this;
  28839. };
  28840. /**
  28841. * Disposes a previously registered javascript function called before the rendering.
  28842. * This function is passed the current mesh.
  28843. * Returns the Mesh.
  28844. */
  28845. Mesh.prototype.unregisterBeforeRender = function (func) {
  28846. this.onBeforeRenderObservable.removeCallback(func);
  28847. return this;
  28848. };
  28849. /**
  28850. * Registers for this mesh a javascript function called just after the rendering is complete.
  28851. * This function is passed the current mesh.
  28852. * Returns the Mesh.
  28853. */
  28854. Mesh.prototype.registerAfterRender = function (func) {
  28855. this.onAfterRenderObservable.add(func);
  28856. return this;
  28857. };
  28858. /**
  28859. * Disposes a previously registered javascript function called after the rendering.
  28860. * This function is passed the current mesh.
  28861. * Return the Mesh.
  28862. */
  28863. Mesh.prototype.unregisterAfterRender = function (func) {
  28864. this.onAfterRenderObservable.removeCallback(func);
  28865. return this;
  28866. };
  28867. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28868. var scene = this.getScene();
  28869. this._batchCache.mustReturn = false;
  28870. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28871. this._batchCache.visibleInstances[subMeshId] = null;
  28872. if (this._visibleInstances) {
  28873. var currentRenderId = scene.getRenderId();
  28874. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28875. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28876. var selfRenderId = this._renderId;
  28877. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28878. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28879. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28880. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28881. }
  28882. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28883. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28884. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28885. this._batchCache.mustReturn = true;
  28886. return this._batchCache;
  28887. }
  28888. if (currentRenderId !== selfRenderId) {
  28889. this._batchCache.renderSelf[subMeshId] = false;
  28890. }
  28891. }
  28892. this._renderIdForInstances[subMeshId] = currentRenderId;
  28893. }
  28894. return this._batchCache;
  28895. };
  28896. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28897. var visibleInstances = batch.visibleInstances[subMesh._id];
  28898. if (!visibleInstances) {
  28899. return this;
  28900. }
  28901. var matricesCount = visibleInstances.length + 1;
  28902. var bufferSize = matricesCount * 16 * 4;
  28903. var currentInstancesBufferSize = this._instancesBufferSize;
  28904. var instancesBuffer = this._instancesBuffer;
  28905. while (this._instancesBufferSize < bufferSize) {
  28906. this._instancesBufferSize *= 2;
  28907. }
  28908. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28909. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28910. }
  28911. var offset = 0;
  28912. var instancesCount = 0;
  28913. var world = this.getWorldMatrix();
  28914. if (batch.renderSelf[subMesh._id]) {
  28915. world.copyToArray(this._instancesData, offset);
  28916. offset += 16;
  28917. instancesCount++;
  28918. }
  28919. if (visibleInstances) {
  28920. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28921. var instance = visibleInstances[instanceIndex];
  28922. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28923. offset += 16;
  28924. instancesCount++;
  28925. }
  28926. }
  28927. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28928. if (instancesBuffer) {
  28929. instancesBuffer.dispose();
  28930. }
  28931. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28932. this._instancesBuffer = instancesBuffer;
  28933. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28934. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28935. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28936. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28937. }
  28938. else {
  28939. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28940. }
  28941. this._bind(subMesh, effect, fillMode);
  28942. this._draw(subMesh, fillMode, instancesCount);
  28943. engine.unbindInstanceAttributes();
  28944. return this;
  28945. };
  28946. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28947. var scene = this.getScene();
  28948. var engine = scene.getEngine();
  28949. if (hardwareInstancedRendering) {
  28950. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28951. }
  28952. else {
  28953. if (batch.renderSelf[subMesh._id]) {
  28954. // Draw
  28955. if (onBeforeDraw) {
  28956. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28957. }
  28958. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28959. }
  28960. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28961. if (visibleInstancesForSubMesh) {
  28962. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28963. var instance = visibleInstancesForSubMesh[instanceIndex];
  28964. // World
  28965. var world = instance.getWorldMatrix();
  28966. if (onBeforeDraw) {
  28967. onBeforeDraw(true, world, effectiveMaterial);
  28968. }
  28969. // Draw
  28970. this._draw(subMesh, fillMode);
  28971. }
  28972. }
  28973. }
  28974. return this;
  28975. };
  28976. /**
  28977. * Triggers the draw call for the mesh.
  28978. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28979. * Returns the Mesh.
  28980. */
  28981. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28982. this.checkOcclusionQuery();
  28983. if (this._isOccluded) {
  28984. return this;
  28985. }
  28986. var scene = this.getScene();
  28987. // Managing instances
  28988. var batch = this._getInstancesRenderList(subMesh._id);
  28989. if (batch.mustReturn) {
  28990. return this;
  28991. }
  28992. // Checking geometry state
  28993. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28994. return this;
  28995. }
  28996. this.onBeforeRenderObservable.notifyObservers(this);
  28997. var engine = scene.getEngine();
  28998. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28999. // Material
  29000. var material = subMesh.getMaterial();
  29001. if (!material) {
  29002. return this;
  29003. }
  29004. this._effectiveMaterial = material;
  29005. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29006. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  29007. return this;
  29008. }
  29009. }
  29010. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  29011. return this;
  29012. }
  29013. // Alpha mode
  29014. if (enableAlphaMode) {
  29015. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  29016. }
  29017. // Outline - step 1
  29018. var savedDepthWrite = engine.getDepthWrite();
  29019. if (this.renderOutline) {
  29020. engine.setDepthWrite(false);
  29021. scene.getOutlineRenderer().render(subMesh, batch);
  29022. engine.setDepthWrite(savedDepthWrite);
  29023. }
  29024. var effect;
  29025. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29026. effect = subMesh.effect;
  29027. }
  29028. else {
  29029. effect = this._effectiveMaterial.getEffect();
  29030. }
  29031. if (!effect) {
  29032. return this;
  29033. }
  29034. var sideOrientation = this.overrideMaterialSideOrientation;
  29035. if (sideOrientation == null) {
  29036. sideOrientation = this._effectiveMaterial.sideOrientation;
  29037. if (this._getWorldMatrixDeterminant() < 0) {
  29038. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29039. }
  29040. }
  29041. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29042. if (this._effectiveMaterial.forceDepthWrite) {
  29043. engine.setDepthWrite(true);
  29044. }
  29045. // Bind
  29046. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29047. if (!hardwareInstancedRendering) {
  29048. this._bind(subMesh, effect, fillMode);
  29049. }
  29050. var world = this.getWorldMatrix();
  29051. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29052. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29053. }
  29054. else {
  29055. this._effectiveMaterial.bind(world, this);
  29056. }
  29057. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29058. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29059. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29060. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29061. }
  29062. // Draw
  29063. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29064. // Unbind
  29065. this._effectiveMaterial.unbind();
  29066. // Outline - step 2
  29067. if (this.renderOutline && savedDepthWrite) {
  29068. engine.setDepthWrite(true);
  29069. engine.setColorWrite(false);
  29070. scene.getOutlineRenderer().render(subMesh, batch);
  29071. engine.setColorWrite(true);
  29072. }
  29073. // Overlay
  29074. if (this.renderOverlay) {
  29075. var currentMode = engine.getAlphaMode();
  29076. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29077. scene.getOutlineRenderer().render(subMesh, batch, true);
  29078. engine.setAlphaMode(currentMode);
  29079. }
  29080. this.onAfterRenderObservable.notifyObservers(this);
  29081. return this;
  29082. };
  29083. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29084. if (isInstance && effectiveMaterial) {
  29085. effectiveMaterial.bindOnlyWorldMatrix(world);
  29086. }
  29087. };
  29088. /**
  29089. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29090. */
  29091. Mesh.prototype.getEmittedParticleSystems = function () {
  29092. var results = new Array();
  29093. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29094. var particleSystem = this.getScene().particleSystems[index];
  29095. if (particleSystem.emitter === this) {
  29096. results.push(particleSystem);
  29097. }
  29098. }
  29099. return results;
  29100. };
  29101. /**
  29102. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29103. */
  29104. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29105. var results = new Array();
  29106. var descendants = this.getDescendants();
  29107. descendants.push(this);
  29108. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29109. var particleSystem = this.getScene().particleSystems[index];
  29110. var emitter = particleSystem.emitter;
  29111. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29112. results.push(particleSystem);
  29113. }
  29114. }
  29115. return results;
  29116. };
  29117. Mesh.prototype._checkDelayState = function () {
  29118. var scene = this.getScene();
  29119. if (this._geometry) {
  29120. this._geometry.load(scene);
  29121. }
  29122. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29123. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29124. this._queueLoad(scene);
  29125. }
  29126. return this;
  29127. };
  29128. Mesh.prototype._queueLoad = function (scene) {
  29129. var _this = this;
  29130. scene._addPendingData(this);
  29131. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29132. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29133. if (data instanceof ArrayBuffer) {
  29134. _this._delayLoadingFunction(data, _this);
  29135. }
  29136. else {
  29137. _this._delayLoadingFunction(JSON.parse(data), _this);
  29138. }
  29139. _this.instances.forEach(function (instance) {
  29140. instance._syncSubMeshes();
  29141. });
  29142. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29143. scene._removePendingData(_this);
  29144. }, function () { }, scene.database, getBinaryData);
  29145. return this;
  29146. };
  29147. /**
  29148. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29149. */
  29150. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29151. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29152. return false;
  29153. }
  29154. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29155. return false;
  29156. }
  29157. this._checkDelayState();
  29158. return true;
  29159. };
  29160. /**
  29161. * Sets the mesh material by the material or multiMaterial `id` property.
  29162. * The material `id` is a string identifying the material or the multiMaterial.
  29163. * This method returns the Mesh.
  29164. */
  29165. Mesh.prototype.setMaterialByID = function (id) {
  29166. var materials = this.getScene().materials;
  29167. var index;
  29168. for (index = materials.length - 1; index > -1; index--) {
  29169. if (materials[index].id === id) {
  29170. this.material = materials[index];
  29171. return this;
  29172. }
  29173. }
  29174. // Multi
  29175. var multiMaterials = this.getScene().multiMaterials;
  29176. for (index = multiMaterials.length - 1; index > -1; index--) {
  29177. if (multiMaterials[index].id === id) {
  29178. this.material = multiMaterials[index];
  29179. return this;
  29180. }
  29181. }
  29182. return this;
  29183. };
  29184. /**
  29185. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29186. */
  29187. Mesh.prototype.getAnimatables = function () {
  29188. var results = new Array();
  29189. if (this.material) {
  29190. results.push(this.material);
  29191. }
  29192. if (this.skeleton) {
  29193. results.push(this.skeleton);
  29194. }
  29195. return results;
  29196. };
  29197. /**
  29198. * Modifies the mesh geometry according to the passed transformation matrix.
  29199. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29200. * The mesh normals are modified accordingly the same transformation.
  29201. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29202. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29203. * Returns the Mesh.
  29204. */
  29205. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29206. // Position
  29207. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29208. return this;
  29209. }
  29210. var submeshes = this.subMeshes.splice(0);
  29211. this._resetPointsArrayCache();
  29212. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29213. var temp = new Array();
  29214. var index;
  29215. for (index = 0; index < data.length; index += 3) {
  29216. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29217. }
  29218. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29219. // Normals
  29220. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29221. return this;
  29222. }
  29223. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29224. temp = [];
  29225. for (index = 0; index < data.length; index += 3) {
  29226. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29227. }
  29228. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29229. // flip faces?
  29230. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29231. this.flipFaces();
  29232. }
  29233. // Restore submeshes
  29234. this.releaseSubMeshes();
  29235. this.subMeshes = submeshes;
  29236. return this;
  29237. };
  29238. /**
  29239. * Modifies the mesh geometry according to its own current World Matrix.
  29240. * The mesh World Matrix is then reset.
  29241. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29242. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29243. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29244. * Returns the Mesh.
  29245. */
  29246. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29247. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29248. this.scaling.copyFromFloats(1, 1, 1);
  29249. this.position.copyFromFloats(0, 0, 0);
  29250. this.rotation.copyFromFloats(0, 0, 0);
  29251. //only if quaternion is already set
  29252. if (this.rotationQuaternion) {
  29253. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29254. }
  29255. this._worldMatrix = BABYLON.Matrix.Identity();
  29256. return this;
  29257. };
  29258. Object.defineProperty(Mesh.prototype, "_positions", {
  29259. // Cache
  29260. get: function () {
  29261. if (this._geometry) {
  29262. return this._geometry._positions;
  29263. }
  29264. return null;
  29265. },
  29266. enumerable: true,
  29267. configurable: true
  29268. });
  29269. Mesh.prototype._resetPointsArrayCache = function () {
  29270. if (this._geometry) {
  29271. this._geometry._resetPointsArrayCache();
  29272. }
  29273. return this;
  29274. };
  29275. Mesh.prototype._generatePointsArray = function () {
  29276. if (this._geometry) {
  29277. return this._geometry._generatePointsArray();
  29278. }
  29279. return false;
  29280. };
  29281. /**
  29282. * Returns a new Mesh object generated from the current mesh properties.
  29283. * This method must not get confused with createInstance().
  29284. * The parameter `name` is a string, the name given to the new mesh.
  29285. * The optional parameter `newParent` can be any Node object (default `null`).
  29286. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29287. * 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.
  29288. */
  29289. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29290. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29291. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29292. };
  29293. /**
  29294. * Releases resources associated with this mesh.
  29295. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29296. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29297. */
  29298. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29299. var _this = this;
  29300. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29301. this.morphTargetManager = null;
  29302. if (this._geometry) {
  29303. this._geometry.releaseForMesh(this, true);
  29304. }
  29305. // Sources
  29306. var meshes = this.getScene().meshes;
  29307. meshes.forEach(function (abstractMesh) {
  29308. var mesh = abstractMesh;
  29309. if (mesh._source && mesh._source === _this) {
  29310. mesh._source = null;
  29311. }
  29312. });
  29313. this._source = null;
  29314. // Instances
  29315. if (this._instancesBuffer) {
  29316. this._instancesBuffer.dispose();
  29317. this._instancesBuffer = null;
  29318. }
  29319. while (this.instances.length) {
  29320. this.instances[0].dispose();
  29321. }
  29322. // Effect layers.
  29323. var effectLayers = this.getScene().effectLayers;
  29324. for (var i = 0; i < effectLayers.length; i++) {
  29325. var effectLayer = effectLayers[i];
  29326. if (effectLayer) {
  29327. effectLayer._disposeMesh(this);
  29328. }
  29329. }
  29330. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29331. };
  29332. /**
  29333. * Modifies the mesh geometry according to a displacement map.
  29334. * 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.
  29335. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29336. * This method returns nothing.
  29337. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29338. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29339. * 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.
  29340. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29341. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29342. *
  29343. * Returns the Mesh.
  29344. */
  29345. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29346. var _this = this;
  29347. var scene = this.getScene();
  29348. var onload = function (img) {
  29349. // Getting height map data
  29350. var canvas = document.createElement("canvas");
  29351. var context = canvas.getContext("2d");
  29352. var heightMapWidth = img.width;
  29353. var heightMapHeight = img.height;
  29354. canvas.width = heightMapWidth;
  29355. canvas.height = heightMapHeight;
  29356. context.drawImage(img, 0, 0);
  29357. // Create VertexData from map data
  29358. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29359. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29360. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29361. //execute success callback, if set
  29362. if (onSuccess) {
  29363. onSuccess(_this);
  29364. }
  29365. };
  29366. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29367. return this;
  29368. };
  29369. /**
  29370. * Modifies the mesh geometry according to a displacementMap buffer.
  29371. * 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.
  29372. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29373. * This method returns nothing.
  29374. * 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.
  29375. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29376. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29377. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29378. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29379. *
  29380. * Returns the Mesh.
  29381. */
  29382. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29383. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29384. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29385. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29386. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29387. return this;
  29388. }
  29389. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29390. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29391. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29392. var position = BABYLON.Vector3.Zero();
  29393. var normal = BABYLON.Vector3.Zero();
  29394. var uv = BABYLON.Vector2.Zero();
  29395. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29396. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29397. for (var index = 0; index < positions.length; index += 3) {
  29398. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29399. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29400. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29401. // Compute height
  29402. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29403. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29404. var pos = (u + v * heightMapWidth) * 4;
  29405. var r = buffer[pos] / 255.0;
  29406. var g = buffer[pos + 1] / 255.0;
  29407. var b = buffer[pos + 2] / 255.0;
  29408. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29409. normal.normalize();
  29410. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29411. position = position.add(normal);
  29412. position.toArray(positions, index);
  29413. }
  29414. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29415. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29416. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29417. return this;
  29418. };
  29419. /**
  29420. * Modify the mesh to get a flat shading rendering.
  29421. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29422. * This method returns the Mesh.
  29423. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29424. */
  29425. Mesh.prototype.convertToFlatShadedMesh = function () {
  29426. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29427. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29428. var kinds = this.getVerticesDataKinds();
  29429. var vbs = {};
  29430. var data = {};
  29431. var newdata = {};
  29432. var updatableNormals = false;
  29433. var kindIndex;
  29434. var kind;
  29435. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29436. kind = kinds[kindIndex];
  29437. var vertexBuffer = this.getVertexBuffer(kind);
  29438. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29439. updatableNormals = vertexBuffer.isUpdatable();
  29440. kinds.splice(kindIndex, 1);
  29441. kindIndex--;
  29442. continue;
  29443. }
  29444. vbs[kind] = vertexBuffer;
  29445. data[kind] = vbs[kind].getData();
  29446. newdata[kind] = [];
  29447. }
  29448. // Save previous submeshes
  29449. var previousSubmeshes = this.subMeshes.slice(0);
  29450. var indices = this.getIndices();
  29451. var totalIndices = this.getTotalIndices();
  29452. // Generating unique vertices per face
  29453. var index;
  29454. for (index = 0; index < totalIndices; index++) {
  29455. var vertexIndex = indices[index];
  29456. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29457. kind = kinds[kindIndex];
  29458. var stride = vbs[kind].getStrideSize();
  29459. for (var offset = 0; offset < stride; offset++) {
  29460. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29461. }
  29462. }
  29463. }
  29464. // Updating faces & normal
  29465. var normals = [];
  29466. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29467. for (index = 0; index < totalIndices; index += 3) {
  29468. indices[index] = index;
  29469. indices[index + 1] = index + 1;
  29470. indices[index + 2] = index + 2;
  29471. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29472. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29473. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29474. var p1p2 = p1.subtract(p2);
  29475. var p3p2 = p3.subtract(p2);
  29476. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29477. // Store same normals for every vertex
  29478. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29479. normals.push(normal.x);
  29480. normals.push(normal.y);
  29481. normals.push(normal.z);
  29482. }
  29483. }
  29484. this.setIndices(indices);
  29485. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29486. // Updating vertex buffers
  29487. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29488. kind = kinds[kindIndex];
  29489. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29490. }
  29491. // Updating submeshes
  29492. this.releaseSubMeshes();
  29493. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29494. var previousOne = previousSubmeshes[submeshIndex];
  29495. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29496. }
  29497. this.synchronizeInstances();
  29498. return this;
  29499. };
  29500. /**
  29501. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29502. * In other words, more vertices, no more indices and a single bigger VBO.
  29503. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29504. * Returns the Mesh.
  29505. */
  29506. Mesh.prototype.convertToUnIndexedMesh = function () {
  29507. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29508. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29509. var kinds = this.getVerticesDataKinds();
  29510. var vbs = {};
  29511. var data = {};
  29512. var newdata = {};
  29513. var kindIndex;
  29514. var kind;
  29515. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29516. kind = kinds[kindIndex];
  29517. var vertexBuffer = this.getVertexBuffer(kind);
  29518. vbs[kind] = vertexBuffer;
  29519. data[kind] = vbs[kind].getData();
  29520. newdata[kind] = [];
  29521. }
  29522. // Save previous submeshes
  29523. var previousSubmeshes = this.subMeshes.slice(0);
  29524. var indices = this.getIndices();
  29525. var totalIndices = this.getTotalIndices();
  29526. // Generating unique vertices per face
  29527. var index;
  29528. for (index = 0; index < totalIndices; index++) {
  29529. var vertexIndex = indices[index];
  29530. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29531. kind = kinds[kindIndex];
  29532. var stride = vbs[kind].getStrideSize();
  29533. for (var offset = 0; offset < stride; offset++) {
  29534. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29535. }
  29536. }
  29537. }
  29538. // Updating indices
  29539. for (index = 0; index < totalIndices; index += 3) {
  29540. indices[index] = index;
  29541. indices[index + 1] = index + 1;
  29542. indices[index + 2] = index + 2;
  29543. }
  29544. this.setIndices(indices);
  29545. // Updating vertex buffers
  29546. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29547. kind = kinds[kindIndex];
  29548. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29549. }
  29550. // Updating submeshes
  29551. this.releaseSubMeshes();
  29552. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29553. var previousOne = previousSubmeshes[submeshIndex];
  29554. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29555. }
  29556. this._unIndexed = true;
  29557. this.synchronizeInstances();
  29558. return this;
  29559. };
  29560. /**
  29561. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29562. * This method returns the Mesh.
  29563. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29564. */
  29565. Mesh.prototype.flipFaces = function (flipNormals) {
  29566. if (flipNormals === void 0) { flipNormals = false; }
  29567. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29568. var i;
  29569. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29570. for (i = 0; i < vertex_data.normals.length; i++) {
  29571. vertex_data.normals[i] *= -1;
  29572. }
  29573. }
  29574. if (vertex_data.indices) {
  29575. var temp;
  29576. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29577. // reassign indices
  29578. temp = vertex_data.indices[i + 1];
  29579. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29580. vertex_data.indices[i + 2] = temp;
  29581. }
  29582. }
  29583. vertex_data.applyToMesh(this);
  29584. return this;
  29585. };
  29586. // Instances
  29587. /**
  29588. * Creates a new InstancedMesh object from the mesh model.
  29589. * An instance shares the same properties and the same material than its model.
  29590. * Only these properties of each instance can then be set individually :
  29591. * - position
  29592. * - rotation
  29593. * - rotationQuaternion
  29594. * - setPivotMatrix
  29595. * - scaling
  29596. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29597. * Warning : this method is not supported for Line mesh and LineSystem
  29598. */
  29599. Mesh.prototype.createInstance = function (name) {
  29600. return new BABYLON.InstancedMesh(name, this);
  29601. };
  29602. /**
  29603. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29604. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29605. * This method returns the Mesh.
  29606. */
  29607. Mesh.prototype.synchronizeInstances = function () {
  29608. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29609. var instance = this.instances[instanceIndex];
  29610. instance._syncSubMeshes();
  29611. }
  29612. return this;
  29613. };
  29614. /**
  29615. * Simplify the mesh according to the given array of settings.
  29616. * Function will return immediately and will simplify async. It returns the Mesh.
  29617. * @param settings a collection of simplification settings.
  29618. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29619. * @param type the type of simplification to run.
  29620. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29621. */
  29622. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29623. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29624. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29625. this.getScene().simplificationQueue.addTask({
  29626. settings: settings,
  29627. parallelProcessing: parallelProcessing,
  29628. mesh: this,
  29629. simplificationType: simplificationType,
  29630. successCallback: successCallback
  29631. });
  29632. return this;
  29633. };
  29634. /**
  29635. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29636. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29637. * This should be used together with the simplification to avoid disappearing triangles.
  29638. * Returns the Mesh.
  29639. * @param successCallback an optional success callback to be called after the optimization finished.
  29640. */
  29641. Mesh.prototype.optimizeIndices = function (successCallback) {
  29642. var _this = this;
  29643. var indices = this.getIndices();
  29644. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29645. if (!positions || !indices) {
  29646. return this;
  29647. }
  29648. var vectorPositions = new Array();
  29649. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29650. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29651. }
  29652. var dupes = new Array();
  29653. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29654. var realPos = vectorPositions.length - 1 - iteration;
  29655. var testedPosition = vectorPositions[realPos];
  29656. for (var j = 0; j < realPos; ++j) {
  29657. var againstPosition = vectorPositions[j];
  29658. if (testedPosition.equals(againstPosition)) {
  29659. dupes[realPos] = j;
  29660. break;
  29661. }
  29662. }
  29663. }, function () {
  29664. for (var i = 0; i < indices.length; ++i) {
  29665. indices[i] = dupes[indices[i]] || indices[i];
  29666. }
  29667. //indices are now reordered
  29668. var originalSubMeshes = _this.subMeshes.slice(0);
  29669. _this.setIndices(indices);
  29670. _this.subMeshes = originalSubMeshes;
  29671. if (successCallback) {
  29672. successCallback(_this);
  29673. }
  29674. });
  29675. return this;
  29676. };
  29677. Mesh.prototype.serialize = function (serializationObject) {
  29678. serializationObject.name = this.name;
  29679. serializationObject.id = this.id;
  29680. serializationObject.type = this.getClassName();
  29681. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29682. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29683. }
  29684. serializationObject.position = this.position.asArray();
  29685. if (this.rotationQuaternion) {
  29686. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29687. }
  29688. else if (this.rotation) {
  29689. serializationObject.rotation = this.rotation.asArray();
  29690. }
  29691. serializationObject.scaling = this.scaling.asArray();
  29692. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29693. serializationObject.isEnabled = this.isEnabled(false);
  29694. serializationObject.isVisible = this.isVisible;
  29695. serializationObject.infiniteDistance = this.infiniteDistance;
  29696. serializationObject.pickable = this.isPickable;
  29697. serializationObject.receiveShadows = this.receiveShadows;
  29698. serializationObject.billboardMode = this.billboardMode;
  29699. serializationObject.visibility = this.visibility;
  29700. serializationObject.checkCollisions = this.checkCollisions;
  29701. serializationObject.isBlocker = this.isBlocker;
  29702. // Parent
  29703. if (this.parent) {
  29704. serializationObject.parentId = this.parent.id;
  29705. }
  29706. // Geometry
  29707. serializationObject.isUnIndexed = this.isUnIndexed;
  29708. var geometry = this._geometry;
  29709. if (geometry) {
  29710. var geometryId = geometry.id;
  29711. serializationObject.geometryId = geometryId;
  29712. // SubMeshes
  29713. serializationObject.subMeshes = [];
  29714. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29715. var subMesh = this.subMeshes[subIndex];
  29716. serializationObject.subMeshes.push({
  29717. materialIndex: subMesh.materialIndex,
  29718. verticesStart: subMesh.verticesStart,
  29719. verticesCount: subMesh.verticesCount,
  29720. indexStart: subMesh.indexStart,
  29721. indexCount: subMesh.indexCount
  29722. });
  29723. }
  29724. }
  29725. // Material
  29726. if (this.material) {
  29727. serializationObject.materialId = this.material.id;
  29728. }
  29729. else {
  29730. this.material = null;
  29731. }
  29732. // Morph targets
  29733. if (this.morphTargetManager) {
  29734. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29735. }
  29736. // Skeleton
  29737. if (this.skeleton) {
  29738. serializationObject.skeletonId = this.skeleton.id;
  29739. }
  29740. // Physics
  29741. //TODO implement correct serialization for physics impostors.
  29742. var impostor = this.getPhysicsImpostor();
  29743. if (impostor) {
  29744. serializationObject.physicsMass = impostor.getParam("mass");
  29745. serializationObject.physicsFriction = impostor.getParam("friction");
  29746. serializationObject.physicsRestitution = impostor.getParam("mass");
  29747. serializationObject.physicsImpostor = impostor.type;
  29748. }
  29749. // Metadata
  29750. if (this.metadata) {
  29751. serializationObject.metadata = this.metadata;
  29752. }
  29753. // Instances
  29754. serializationObject.instances = [];
  29755. for (var index = 0; index < this.instances.length; index++) {
  29756. var instance = this.instances[index];
  29757. var serializationInstance = {
  29758. name: instance.name,
  29759. id: instance.id,
  29760. position: instance.position.asArray(),
  29761. scaling: instance.scaling.asArray()
  29762. };
  29763. if (instance.rotationQuaternion) {
  29764. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29765. }
  29766. else if (instance.rotation) {
  29767. serializationInstance.rotation = instance.rotation.asArray();
  29768. }
  29769. serializationObject.instances.push(serializationInstance);
  29770. // Animations
  29771. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29772. serializationInstance.ranges = instance.serializeAnimationRanges();
  29773. }
  29774. //
  29775. // Animations
  29776. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29777. serializationObject.ranges = this.serializeAnimationRanges();
  29778. // Layer mask
  29779. serializationObject.layerMask = this.layerMask;
  29780. // Alpha
  29781. serializationObject.alphaIndex = this.alphaIndex;
  29782. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29783. // Overlay
  29784. serializationObject.overlayAlpha = this.overlayAlpha;
  29785. serializationObject.overlayColor = this.overlayColor.asArray();
  29786. serializationObject.renderOverlay = this.renderOverlay;
  29787. // Fog
  29788. serializationObject.applyFog = this.applyFog;
  29789. // Action Manager
  29790. if (this.actionManager) {
  29791. serializationObject.actions = this.actionManager.serialize(this.name);
  29792. }
  29793. };
  29794. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29795. if (!this.geometry) {
  29796. return;
  29797. }
  29798. this._markSubMeshesAsAttributesDirty();
  29799. var morphTargetManager = this._morphTargetManager;
  29800. if (morphTargetManager && morphTargetManager.vertexCount) {
  29801. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29802. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29803. this.morphTargetManager = null;
  29804. return;
  29805. }
  29806. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29807. var morphTarget = morphTargetManager.getActiveTarget(index);
  29808. var positions = morphTarget.getPositions();
  29809. if (!positions) {
  29810. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29811. return;
  29812. }
  29813. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29814. var normals = morphTarget.getNormals();
  29815. if (normals) {
  29816. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29817. }
  29818. var tangents = morphTarget.getTangents();
  29819. if (tangents) {
  29820. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29821. }
  29822. }
  29823. }
  29824. else {
  29825. var index = 0;
  29826. // Positions
  29827. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29828. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29829. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29830. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29831. }
  29832. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29833. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29834. }
  29835. index++;
  29836. }
  29837. }
  29838. };
  29839. // Statics
  29840. /**
  29841. * Returns a new Mesh object parsed from the source provided.
  29842. * The parameter `parsedMesh` is the source.
  29843. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29844. */
  29845. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29846. var mesh;
  29847. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29848. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29849. }
  29850. else {
  29851. mesh = new Mesh(parsedMesh.name, scene);
  29852. }
  29853. mesh.id = parsedMesh.id;
  29854. if (BABYLON.Tags) {
  29855. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29856. }
  29857. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29858. if (parsedMesh.metadata !== undefined) {
  29859. mesh.metadata = parsedMesh.metadata;
  29860. }
  29861. if (parsedMesh.rotationQuaternion) {
  29862. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29863. }
  29864. else if (parsedMesh.rotation) {
  29865. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29866. }
  29867. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29868. if (parsedMesh.localMatrix) {
  29869. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29870. }
  29871. else if (parsedMesh.pivotMatrix) {
  29872. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29873. }
  29874. mesh.setEnabled(parsedMesh.isEnabled);
  29875. mesh.isVisible = parsedMesh.isVisible;
  29876. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29877. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29878. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29879. if (parsedMesh.applyFog !== undefined) {
  29880. mesh.applyFog = parsedMesh.applyFog;
  29881. }
  29882. if (parsedMesh.pickable !== undefined) {
  29883. mesh.isPickable = parsedMesh.pickable;
  29884. }
  29885. if (parsedMesh.alphaIndex !== undefined) {
  29886. mesh.alphaIndex = parsedMesh.alphaIndex;
  29887. }
  29888. mesh.receiveShadows = parsedMesh.receiveShadows;
  29889. mesh.billboardMode = parsedMesh.billboardMode;
  29890. if (parsedMesh.visibility !== undefined) {
  29891. mesh.visibility = parsedMesh.visibility;
  29892. }
  29893. mesh.checkCollisions = parsedMesh.checkCollisions;
  29894. if (parsedMesh.isBlocker !== undefined) {
  29895. mesh.isBlocker = parsedMesh.isBlocker;
  29896. }
  29897. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29898. // freezeWorldMatrix
  29899. if (parsedMesh.freezeWorldMatrix) {
  29900. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29901. }
  29902. // Parent
  29903. if (parsedMesh.parentId) {
  29904. mesh._waitingParentId = parsedMesh.parentId;
  29905. }
  29906. // Actions
  29907. if (parsedMesh.actions !== undefined) {
  29908. mesh._waitingActions = parsedMesh.actions;
  29909. }
  29910. // Overlay
  29911. if (parsedMesh.overlayAlpha !== undefined) {
  29912. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29913. }
  29914. if (parsedMesh.overlayColor !== undefined) {
  29915. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29916. }
  29917. if (parsedMesh.renderOverlay !== undefined) {
  29918. mesh.renderOverlay = parsedMesh.renderOverlay;
  29919. }
  29920. // Geometry
  29921. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29922. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29923. if (parsedMesh.delayLoadingFile) {
  29924. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29925. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29926. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29927. if (parsedMesh._binaryInfo) {
  29928. mesh._binaryInfo = parsedMesh._binaryInfo;
  29929. }
  29930. mesh._delayInfo = [];
  29931. if (parsedMesh.hasUVs) {
  29932. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29933. }
  29934. if (parsedMesh.hasUVs2) {
  29935. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29936. }
  29937. if (parsedMesh.hasUVs3) {
  29938. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29939. }
  29940. if (parsedMesh.hasUVs4) {
  29941. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29942. }
  29943. if (parsedMesh.hasUVs5) {
  29944. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29945. }
  29946. if (parsedMesh.hasUVs6) {
  29947. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29948. }
  29949. if (parsedMesh.hasColors) {
  29950. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29951. }
  29952. if (parsedMesh.hasMatricesIndices) {
  29953. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29954. }
  29955. if (parsedMesh.hasMatricesWeights) {
  29956. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29957. }
  29958. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29959. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29960. mesh._checkDelayState();
  29961. }
  29962. }
  29963. else {
  29964. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29965. }
  29966. // Material
  29967. if (parsedMesh.materialId) {
  29968. mesh.setMaterialByID(parsedMesh.materialId);
  29969. }
  29970. else {
  29971. mesh.material = null;
  29972. }
  29973. // Morph targets
  29974. if (parsedMesh.morphTargetManagerId > -1) {
  29975. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29976. }
  29977. // Skeleton
  29978. if (parsedMesh.skeletonId > -1) {
  29979. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29980. if (parsedMesh.numBoneInfluencers) {
  29981. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29982. }
  29983. }
  29984. // Animations
  29985. if (parsedMesh.animations) {
  29986. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29987. var parsedAnimation = parsedMesh.animations[animationIndex];
  29988. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29989. }
  29990. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29991. }
  29992. if (parsedMesh.autoAnimate) {
  29993. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29994. }
  29995. // Layer Mask
  29996. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29997. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29998. }
  29999. else {
  30000. mesh.layerMask = 0x0FFFFFFF;
  30001. }
  30002. // Physics
  30003. if (parsedMesh.physicsImpostor) {
  30004. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  30005. mass: parsedMesh.physicsMass,
  30006. friction: parsedMesh.physicsFriction,
  30007. restitution: parsedMesh.physicsRestitution
  30008. }, scene);
  30009. }
  30010. // Instances
  30011. if (parsedMesh.instances) {
  30012. for (var index = 0; index < parsedMesh.instances.length; index++) {
  30013. var parsedInstance = parsedMesh.instances[index];
  30014. var instance = mesh.createInstance(parsedInstance.name);
  30015. if (parsedInstance.id) {
  30016. instance.id = parsedInstance.id;
  30017. }
  30018. if (BABYLON.Tags) {
  30019. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  30020. }
  30021. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  30022. if (parsedInstance.parentId) {
  30023. instance._waitingParentId = parsedInstance.parentId;
  30024. }
  30025. if (parsedInstance.rotationQuaternion) {
  30026. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  30027. }
  30028. else if (parsedInstance.rotation) {
  30029. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  30030. }
  30031. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  30032. instance.checkCollisions = mesh.checkCollisions;
  30033. if (parsedMesh.animations) {
  30034. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30035. parsedAnimation = parsedMesh.animations[animationIndex];
  30036. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30037. }
  30038. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30039. }
  30040. }
  30041. }
  30042. return mesh;
  30043. };
  30044. /**
  30045. * Creates a ribbon mesh.
  30046. * Please consider using the same method from the MeshBuilder class instead.
  30047. * 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.
  30048. *
  30049. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30050. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30051. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30052. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30053. * 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.
  30054. * 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.
  30055. * 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
  30056. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30057. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30058. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30059. */
  30060. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30061. if (closeArray === void 0) { closeArray = false; }
  30062. if (updatable === void 0) { updatable = false; }
  30063. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30064. pathArray: pathArray,
  30065. closeArray: closeArray,
  30066. closePath: closePath,
  30067. offset: offset,
  30068. updatable: updatable,
  30069. sideOrientation: sideOrientation,
  30070. instance: instance
  30071. }, scene);
  30072. };
  30073. /**
  30074. * Creates a plane polygonal mesh. By default, this is a disc.
  30075. * Please consider using the same method from the MeshBuilder class instead.
  30076. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30077. * 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.
  30078. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30079. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30081. */
  30082. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30083. if (scene === void 0) { scene = null; }
  30084. var options = {
  30085. radius: radius,
  30086. tessellation: tessellation,
  30087. sideOrientation: sideOrientation,
  30088. updatable: updatable
  30089. };
  30090. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30091. };
  30092. /**
  30093. * Creates a box mesh.
  30094. * Please consider using the same method from the MeshBuilder class instead.
  30095. * The parameter `size` sets the size (float) of each box side (default 1).
  30096. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30097. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30099. */
  30100. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30101. if (scene === void 0) { scene = null; }
  30102. var options = {
  30103. size: size,
  30104. sideOrientation: sideOrientation,
  30105. updatable: updatable
  30106. };
  30107. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30108. };
  30109. /**
  30110. * Creates a sphere mesh.
  30111. * Please consider using the same method from the MeshBuilder class instead.
  30112. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30113. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30114. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30115. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30116. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30117. */
  30118. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30119. var options = {
  30120. segments: segments,
  30121. diameterX: diameter,
  30122. diameterY: diameter,
  30123. diameterZ: diameter,
  30124. sideOrientation: sideOrientation,
  30125. updatable: updatable
  30126. };
  30127. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30128. };
  30129. /**
  30130. * Creates a cylinder or a cone mesh.
  30131. * Please consider using the same method from the MeshBuilder class instead.
  30132. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30133. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30134. * 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.
  30135. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30136. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30137. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30138. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30139. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30140. */
  30141. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30142. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30143. if (scene !== undefined) {
  30144. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30145. updatable = scene;
  30146. }
  30147. scene = subdivisions;
  30148. subdivisions = 1;
  30149. }
  30150. var options = {
  30151. height: height,
  30152. diameterTop: diameterTop,
  30153. diameterBottom: diameterBottom,
  30154. tessellation: tessellation,
  30155. subdivisions: subdivisions,
  30156. sideOrientation: sideOrientation,
  30157. updatable: updatable
  30158. };
  30159. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30160. };
  30161. // Torus (Code from SharpDX.org)
  30162. /**
  30163. * Creates a torus mesh.
  30164. * Please consider using the same method from the MeshBuilder class instead.
  30165. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30166. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30167. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30168. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30169. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30170. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30171. */
  30172. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30173. var options = {
  30174. diameter: diameter,
  30175. thickness: thickness,
  30176. tessellation: tessellation,
  30177. sideOrientation: sideOrientation,
  30178. updatable: updatable
  30179. };
  30180. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30181. };
  30182. /**
  30183. * Creates a torus knot mesh.
  30184. * Please consider using the same method from the MeshBuilder class instead.
  30185. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30186. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30187. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30188. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30189. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30190. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30192. */
  30193. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30194. var options = {
  30195. radius: radius,
  30196. tube: tube,
  30197. radialSegments: radialSegments,
  30198. tubularSegments: tubularSegments,
  30199. p: p,
  30200. q: q,
  30201. sideOrientation: sideOrientation,
  30202. updatable: updatable
  30203. };
  30204. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30205. };
  30206. /**
  30207. * Creates a line mesh.
  30208. * Please consider using the same method from the MeshBuilder class instead.
  30209. * 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.
  30210. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30211. * The parameter `points` is an array successive Vector3.
  30212. * 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
  30213. * When updating an instance, remember that only point positions can change, not the number of points.
  30214. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30215. */
  30216. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30217. if (scene === void 0) { scene = null; }
  30218. if (updatable === void 0) { updatable = false; }
  30219. if (instance === void 0) { instance = null; }
  30220. var options = {
  30221. points: points,
  30222. updatable: updatable,
  30223. instance: instance
  30224. };
  30225. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30226. };
  30227. /**
  30228. * Creates a dashed line mesh.
  30229. * Please consider using the same method from the MeshBuilder class instead.
  30230. * 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.
  30231. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30232. * The parameter `points` is an array successive Vector3.
  30233. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30234. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30235. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30236. * 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
  30237. * When updating an instance, remember that only point positions can change, not the number of points.
  30238. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30239. */
  30240. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30241. if (scene === void 0) { scene = null; }
  30242. var options = {
  30243. points: points,
  30244. dashSize: dashSize,
  30245. gapSize: gapSize,
  30246. dashNb: dashNb,
  30247. updatable: updatable,
  30248. instance: instance
  30249. };
  30250. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30251. };
  30252. /**
  30253. * Creates a polygon mesh.
  30254. * Please consider using the same method from the MeshBuilder class instead.
  30255. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30256. * 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.
  30257. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30259. * Remember you can only change the shape positions, not their number when updating a polygon.
  30260. */
  30261. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30262. var options = {
  30263. shape: shape,
  30264. holes: holes,
  30265. updatable: updatable,
  30266. sideOrientation: sideOrientation
  30267. };
  30268. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30269. };
  30270. /**
  30271. * Creates an extruded polygon mesh, with depth in the Y direction.
  30272. * Please consider using the same method from the MeshBuilder class instead.
  30273. */
  30274. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30275. var options = {
  30276. shape: shape,
  30277. holes: holes,
  30278. depth: depth,
  30279. updatable: updatable,
  30280. sideOrientation: sideOrientation
  30281. };
  30282. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30283. };
  30284. /**
  30285. * Creates an extruded shape mesh.
  30286. * 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.
  30287. * Please consider using the same method from the MeshBuilder class instead.
  30288. *
  30289. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30290. * 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
  30291. * extruded along the Z axis.
  30292. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30293. * 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.
  30294. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30295. * 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
  30296. * 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
  30297. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30298. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30299. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30301. */
  30302. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30303. if (scene === void 0) { scene = null; }
  30304. var options = {
  30305. shape: shape,
  30306. path: path,
  30307. scale: scale,
  30308. rotation: rotation,
  30309. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30310. sideOrientation: sideOrientation,
  30311. instance: instance,
  30312. updatable: updatable
  30313. };
  30314. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30315. };
  30316. /**
  30317. * Creates an custom extruded shape mesh.
  30318. * 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.
  30319. * Please consider using the same method from the MeshBuilder class instead.
  30320. *
  30321. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30322. * 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
  30323. * extruded along the Z axis.
  30324. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30325. * 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
  30326. * and the distance of this point from the begining of the path :
  30327. * ```javascript
  30328. * var rotationFunction = function(i, distance) {
  30329. * // do things
  30330. * return rotationValue; }
  30331. * ```
  30332. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30333. * 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
  30334. * and the distance of this point from the begining of the path :
  30335. * ```javascript
  30336. * var scaleFunction = function(i, distance) {
  30337. * // do things
  30338. * return scaleValue;}
  30339. * ```
  30340. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30341. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30342. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30343. * 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
  30344. * 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
  30345. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30346. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30347. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30349. */
  30350. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30351. var options = {
  30352. shape: shape,
  30353. path: path,
  30354. scaleFunction: scaleFunction,
  30355. rotationFunction: rotationFunction,
  30356. ribbonCloseArray: ribbonCloseArray,
  30357. ribbonClosePath: ribbonClosePath,
  30358. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30359. sideOrientation: sideOrientation,
  30360. instance: instance,
  30361. updatable: updatable
  30362. };
  30363. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30364. };
  30365. /**
  30366. * Creates lathe mesh.
  30367. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30368. * Please consider using the same method from the MeshBuilder class instead.
  30369. * 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
  30370. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30371. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30372. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30373. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30374. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30375. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30376. */
  30377. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30378. var options = {
  30379. shape: shape,
  30380. radius: radius,
  30381. tessellation: tessellation,
  30382. sideOrientation: sideOrientation,
  30383. updatable: updatable
  30384. };
  30385. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30386. };
  30387. /**
  30388. * Creates a plane mesh.
  30389. * Please consider using the same method from the MeshBuilder class instead.
  30390. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30391. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30392. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30394. */
  30395. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30396. var options = {
  30397. size: size,
  30398. width: size,
  30399. height: size,
  30400. sideOrientation: sideOrientation,
  30401. updatable: updatable
  30402. };
  30403. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30404. };
  30405. /**
  30406. * Creates a ground mesh.
  30407. * Please consider using the same method from the MeshBuilder class instead.
  30408. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30409. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30411. */
  30412. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30413. var options = {
  30414. width: width,
  30415. height: height,
  30416. subdivisions: subdivisions,
  30417. updatable: updatable
  30418. };
  30419. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30420. };
  30421. /**
  30422. * Creates a tiled ground mesh.
  30423. * Please consider using the same method from the MeshBuilder class instead.
  30424. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30425. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30426. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30427. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30428. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30429. * numbers of subdivisions on the ground width and height of each tile.
  30430. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30431. */
  30432. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30433. var options = {
  30434. xmin: xmin,
  30435. zmin: zmin,
  30436. xmax: xmax,
  30437. zmax: zmax,
  30438. subdivisions: subdivisions,
  30439. precision: precision,
  30440. updatable: updatable
  30441. };
  30442. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30443. };
  30444. /**
  30445. * Creates a ground mesh from a height map.
  30446. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30447. * Please consider using the same method from the MeshBuilder class instead.
  30448. * The parameter `url` sets the URL of the height map image resource.
  30449. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30450. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30451. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30452. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30453. * 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).
  30454. * This function is passed the newly built mesh :
  30455. * ```javascript
  30456. * function(mesh) { // do things
  30457. * return; }
  30458. * ```
  30459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30460. */
  30461. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30462. var options = {
  30463. width: width,
  30464. height: height,
  30465. subdivisions: subdivisions,
  30466. minHeight: minHeight,
  30467. maxHeight: maxHeight,
  30468. updatable: updatable,
  30469. onReady: onReady
  30470. };
  30471. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30472. };
  30473. /**
  30474. * Creates a tube mesh.
  30475. * 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.
  30476. * Please consider using the same method from the MeshBuilder class instead.
  30477. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30478. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30479. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30480. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30481. * 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.
  30482. * It must return a radius value (positive float) :
  30483. * ```javascript
  30484. * var radiusFunction = function(i, distance) {
  30485. * // do things
  30486. * return radius; }
  30487. * ```
  30488. * 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
  30489. * 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
  30490. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30491. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30493. */
  30494. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30495. var options = {
  30496. path: path,
  30497. radius: radius,
  30498. tessellation: tessellation,
  30499. radiusFunction: radiusFunction,
  30500. arc: 1,
  30501. cap: cap,
  30502. updatable: updatable,
  30503. sideOrientation: sideOrientation,
  30504. instance: instance
  30505. };
  30506. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30507. };
  30508. /**
  30509. * Creates a polyhedron mesh.
  30510. * Please consider using the same method from the MeshBuilder class instead.
  30511. * 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
  30512. * to choose the wanted type.
  30513. * The parameter `size` (positive float, default 1) sets the polygon size.
  30514. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30515. * 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`.
  30516. * 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
  30517. * 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)`).
  30518. * 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
  30519. * 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.
  30520. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30521. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30522. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30523. */
  30524. Mesh.CreatePolyhedron = function (name, options, scene) {
  30525. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30526. };
  30527. /**
  30528. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30529. * Please consider using the same method from the MeshBuilder class instead.
  30530. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30531. * 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`).
  30532. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30533. * 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.
  30534. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30535. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30537. */
  30538. Mesh.CreateIcoSphere = function (name, options, scene) {
  30539. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30540. };
  30541. /**
  30542. * Creates a decal mesh.
  30543. * Please consider using the same method from the MeshBuilder class instead.
  30544. * 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.
  30545. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30546. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30547. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30548. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30549. */
  30550. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30551. var options = {
  30552. position: position,
  30553. normal: normal,
  30554. size: size,
  30555. angle: angle
  30556. };
  30557. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30558. };
  30559. // Skeletons
  30560. /**
  30561. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30562. */
  30563. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30564. if (!this._sourcePositions) {
  30565. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30566. if (!source) {
  30567. return this._sourcePositions;
  30568. }
  30569. this._sourcePositions = new Float32Array(source);
  30570. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30571. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30572. }
  30573. }
  30574. return this._sourcePositions;
  30575. };
  30576. /**
  30577. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30578. */
  30579. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30580. if (!this._sourceNormals) {
  30581. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30582. if (!source) {
  30583. return this._sourceNormals;
  30584. }
  30585. this._sourceNormals = new Float32Array(source);
  30586. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30587. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30588. }
  30589. }
  30590. return this._sourceNormals;
  30591. };
  30592. /**
  30593. * Updates the vertex buffer by applying transformation from the bones.
  30594. * Returns the Mesh.
  30595. *
  30596. * @param {skeleton} skeleton to apply
  30597. */
  30598. Mesh.prototype.applySkeleton = function (skeleton) {
  30599. if (!this.geometry) {
  30600. return this;
  30601. }
  30602. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30603. return this;
  30604. }
  30605. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30606. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30607. return this;
  30608. }
  30609. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30610. return this;
  30611. }
  30612. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30613. return this;
  30614. }
  30615. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30616. return this;
  30617. }
  30618. if (!this._sourcePositions) {
  30619. var submeshes = this.subMeshes.slice();
  30620. this.setPositionsForCPUSkinning();
  30621. this.subMeshes = submeshes;
  30622. }
  30623. if (!this._sourceNormals) {
  30624. this.setNormalsForCPUSkinning();
  30625. }
  30626. // positionsData checks for not being Float32Array will only pass at most once
  30627. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30628. if (!positionsData) {
  30629. return this;
  30630. }
  30631. if (!(positionsData instanceof Float32Array)) {
  30632. positionsData = new Float32Array(positionsData);
  30633. }
  30634. // normalsData checks for not being Float32Array will only pass at most once
  30635. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30636. if (!normalsData) {
  30637. return this;
  30638. }
  30639. if (!(normalsData instanceof Float32Array)) {
  30640. normalsData = new Float32Array(normalsData);
  30641. }
  30642. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30643. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30644. if (!matricesWeightsData || !matricesIndicesData) {
  30645. return this;
  30646. }
  30647. var needExtras = this.numBoneInfluencers > 4;
  30648. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30649. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30650. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30651. var tempVector3 = BABYLON.Vector3.Zero();
  30652. var finalMatrix = new BABYLON.Matrix();
  30653. var tempMatrix = new BABYLON.Matrix();
  30654. var matWeightIdx = 0;
  30655. var inf;
  30656. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30657. var weight;
  30658. for (inf = 0; inf < 4; inf++) {
  30659. weight = matricesWeightsData[matWeightIdx + inf];
  30660. if (weight > 0) {
  30661. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30662. finalMatrix.addToSelf(tempMatrix);
  30663. }
  30664. else
  30665. break;
  30666. }
  30667. if (needExtras) {
  30668. for (inf = 0; inf < 4; inf++) {
  30669. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30670. if (weight > 0) {
  30671. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30672. finalMatrix.addToSelf(tempMatrix);
  30673. }
  30674. else
  30675. break;
  30676. }
  30677. }
  30678. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30679. tempVector3.toArray(positionsData, index);
  30680. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30681. tempVector3.toArray(normalsData, index);
  30682. finalMatrix.reset();
  30683. }
  30684. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30685. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30686. return this;
  30687. };
  30688. // Tools
  30689. /**
  30690. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30691. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30692. */
  30693. Mesh.MinMax = function (meshes) {
  30694. var minVector = null;
  30695. var maxVector = null;
  30696. meshes.forEach(function (mesh, index, array) {
  30697. var boundingInfo = mesh.getBoundingInfo();
  30698. var boundingBox = boundingInfo.boundingBox;
  30699. if (!minVector || !maxVector) {
  30700. minVector = boundingBox.minimumWorld;
  30701. maxVector = boundingBox.maximumWorld;
  30702. }
  30703. else {
  30704. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30705. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30706. }
  30707. });
  30708. if (!minVector || !maxVector) {
  30709. return {
  30710. min: BABYLON.Vector3.Zero(),
  30711. max: BABYLON.Vector3.Zero()
  30712. };
  30713. }
  30714. return {
  30715. min: minVector,
  30716. max: maxVector
  30717. };
  30718. };
  30719. /**
  30720. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30721. */
  30722. Mesh.Center = function (meshesOrMinMaxVector) {
  30723. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30724. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30725. };
  30726. /**
  30727. * Merge the array of meshes into a single mesh for performance reasons.
  30728. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30729. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30730. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30731. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30732. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30733. */
  30734. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30735. if (disposeSource === void 0) { disposeSource = true; }
  30736. var index;
  30737. if (!allow32BitsIndices) {
  30738. var totalVertices = 0;
  30739. // Counting vertices
  30740. for (index = 0; index < meshes.length; index++) {
  30741. if (meshes[index]) {
  30742. totalVertices += meshes[index].getTotalVertices();
  30743. if (totalVertices > 65536) {
  30744. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30745. return null;
  30746. }
  30747. }
  30748. }
  30749. }
  30750. // Merge
  30751. var vertexData = null;
  30752. var otherVertexData;
  30753. var indiceArray = new Array();
  30754. var source = null;
  30755. for (index = 0; index < meshes.length; index++) {
  30756. if (meshes[index]) {
  30757. meshes[index].computeWorldMatrix(true);
  30758. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30759. otherVertexData.transform(meshes[index].getWorldMatrix());
  30760. if (vertexData) {
  30761. vertexData.merge(otherVertexData);
  30762. }
  30763. else {
  30764. vertexData = otherVertexData;
  30765. source = meshes[index];
  30766. }
  30767. if (subdivideWithSubMeshes) {
  30768. indiceArray.push(meshes[index].getTotalIndices());
  30769. }
  30770. }
  30771. }
  30772. source = source;
  30773. if (!meshSubclass) {
  30774. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30775. }
  30776. vertexData.applyToMesh(meshSubclass);
  30777. // Setting properties
  30778. meshSubclass.material = source.material;
  30779. meshSubclass.checkCollisions = source.checkCollisions;
  30780. // Cleaning
  30781. if (disposeSource) {
  30782. for (index = 0; index < meshes.length; index++) {
  30783. if (meshes[index]) {
  30784. meshes[index].dispose();
  30785. }
  30786. }
  30787. }
  30788. // Subdivide
  30789. if (subdivideWithSubMeshes) {
  30790. //-- Suppresions du submesh global
  30791. meshSubclass.releaseSubMeshes();
  30792. index = 0;
  30793. var offset = 0;
  30794. //-- aplique la subdivision en fonction du tableau d'indices
  30795. while (index < indiceArray.length) {
  30796. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30797. offset += indiceArray[index];
  30798. index++;
  30799. }
  30800. }
  30801. return meshSubclass;
  30802. };
  30803. // Consts
  30804. Mesh._FRONTSIDE = 0;
  30805. Mesh._BACKSIDE = 1;
  30806. Mesh._DOUBLESIDE = 2;
  30807. Mesh._DEFAULTSIDE = 0;
  30808. Mesh._NO_CAP = 0;
  30809. Mesh._CAP_START = 1;
  30810. Mesh._CAP_END = 2;
  30811. Mesh._CAP_ALL = 3;
  30812. return Mesh;
  30813. }(BABYLON.AbstractMesh));
  30814. BABYLON.Mesh = Mesh;
  30815. })(BABYLON || (BABYLON = {}));
  30816. //# sourceMappingURL=babylon.mesh.js.map
  30817. "use strict";
  30818. var BABYLON;
  30819. (function (BABYLON) {
  30820. var BaseSubMesh = /** @class */ (function () {
  30821. function BaseSubMesh() {
  30822. }
  30823. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30824. get: function () {
  30825. return this._materialEffect;
  30826. },
  30827. enumerable: true,
  30828. configurable: true
  30829. });
  30830. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30831. if (defines === void 0) { defines = null; }
  30832. if (this._materialEffect === effect) {
  30833. if (!effect) {
  30834. this._materialDefines = null;
  30835. }
  30836. return;
  30837. }
  30838. this._materialDefines = defines;
  30839. this._materialEffect = effect;
  30840. };
  30841. return BaseSubMesh;
  30842. }());
  30843. BABYLON.BaseSubMesh = BaseSubMesh;
  30844. var SubMesh = /** @class */ (function (_super) {
  30845. __extends(SubMesh, _super);
  30846. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30847. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30848. var _this = _super.call(this) || this;
  30849. _this.materialIndex = materialIndex;
  30850. _this.verticesStart = verticesStart;
  30851. _this.verticesCount = verticesCount;
  30852. _this.indexStart = indexStart;
  30853. _this.indexCount = indexCount;
  30854. _this._renderId = 0;
  30855. _this._mesh = mesh;
  30856. _this._renderingMesh = renderingMesh || mesh;
  30857. mesh.subMeshes.push(_this);
  30858. _this._trianglePlanes = [];
  30859. _this._id = mesh.subMeshes.length - 1;
  30860. if (createBoundingBox) {
  30861. _this.refreshBoundingInfo();
  30862. mesh.computeWorldMatrix(true);
  30863. }
  30864. return _this;
  30865. }
  30866. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30867. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30868. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30869. };
  30870. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30871. get: function () {
  30872. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30873. },
  30874. enumerable: true,
  30875. configurable: true
  30876. });
  30877. /**
  30878. * Returns the submesh BoudingInfo object.
  30879. */
  30880. SubMesh.prototype.getBoundingInfo = function () {
  30881. if (this.IsGlobal) {
  30882. return this._mesh.getBoundingInfo();
  30883. }
  30884. return this._boundingInfo;
  30885. };
  30886. /**
  30887. * Sets the submesh BoundingInfo.
  30888. * Return the SubMesh.
  30889. */
  30890. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30891. this._boundingInfo = boundingInfo;
  30892. return this;
  30893. };
  30894. /**
  30895. * Returns the mesh of the current submesh.
  30896. */
  30897. SubMesh.prototype.getMesh = function () {
  30898. return this._mesh;
  30899. };
  30900. /**
  30901. * Returns the rendering mesh of the submesh.
  30902. */
  30903. SubMesh.prototype.getRenderingMesh = function () {
  30904. return this._renderingMesh;
  30905. };
  30906. /**
  30907. * Returns the submesh material.
  30908. */
  30909. SubMesh.prototype.getMaterial = function () {
  30910. var rootMaterial = this._renderingMesh.material;
  30911. if (rootMaterial === null || rootMaterial === undefined) {
  30912. return this._mesh.getScene().defaultMaterial;
  30913. }
  30914. else if (rootMaterial.getSubMaterial) {
  30915. var multiMaterial = rootMaterial;
  30916. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30917. if (this._currentMaterial !== effectiveMaterial) {
  30918. this._currentMaterial = effectiveMaterial;
  30919. this._materialDefines = null;
  30920. }
  30921. return effectiveMaterial;
  30922. }
  30923. return rootMaterial;
  30924. };
  30925. // Methods
  30926. /**
  30927. * Sets a new updated BoundingInfo object to the submesh.
  30928. * Returns the SubMesh.
  30929. */
  30930. SubMesh.prototype.refreshBoundingInfo = function () {
  30931. this._lastColliderWorldVertices = null;
  30932. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30933. return this;
  30934. }
  30935. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30936. if (!data) {
  30937. this._boundingInfo = this._mesh.getBoundingInfo();
  30938. return this;
  30939. }
  30940. var indices = this._renderingMesh.getIndices();
  30941. var extend;
  30942. //is this the only submesh?
  30943. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30944. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30945. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30946. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30947. }
  30948. else {
  30949. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30950. }
  30951. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30952. return this;
  30953. };
  30954. SubMesh.prototype._checkCollision = function (collider) {
  30955. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30956. return boundingInfo._checkCollision(collider);
  30957. };
  30958. /**
  30959. * Updates the submesh BoundingInfo.
  30960. * Returns the Submesh.
  30961. */
  30962. SubMesh.prototype.updateBoundingInfo = function (world) {
  30963. var boundingInfo = this.getBoundingInfo();
  30964. if (!boundingInfo) {
  30965. this.refreshBoundingInfo();
  30966. boundingInfo = this.getBoundingInfo();
  30967. }
  30968. boundingInfo.update(world);
  30969. return this;
  30970. };
  30971. /**
  30972. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30973. * Boolean returned.
  30974. */
  30975. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30976. var boundingInfo = this.getBoundingInfo();
  30977. if (!boundingInfo) {
  30978. return false;
  30979. }
  30980. return boundingInfo.isInFrustum(frustumPlanes);
  30981. };
  30982. /**
  30983. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30984. * Boolean returned.
  30985. */
  30986. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30987. var boundingInfo = this.getBoundingInfo();
  30988. if (!boundingInfo) {
  30989. return false;
  30990. }
  30991. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30992. };
  30993. /**
  30994. * Renders the submesh.
  30995. * Returns it.
  30996. */
  30997. SubMesh.prototype.render = function (enableAlphaMode) {
  30998. this._renderingMesh.render(this, enableAlphaMode);
  30999. return this;
  31000. };
  31001. /**
  31002. * Returns a new Index Buffer.
  31003. * Type returned : WebGLBuffer.
  31004. */
  31005. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  31006. if (!this._linesIndexBuffer) {
  31007. var linesIndices = [];
  31008. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31009. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  31010. }
  31011. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  31012. this.linesIndexCount = linesIndices.length;
  31013. }
  31014. return this._linesIndexBuffer;
  31015. };
  31016. /**
  31017. * True is the passed Ray intersects the submesh bounding box.
  31018. * Boolean returned.
  31019. */
  31020. SubMesh.prototype.canIntersects = function (ray) {
  31021. var boundingInfo = this.getBoundingInfo();
  31022. if (!boundingInfo) {
  31023. return false;
  31024. }
  31025. return ray.intersectsBox(boundingInfo.boundingBox);
  31026. };
  31027. /**
  31028. * Returns an object IntersectionInfo.
  31029. */
  31030. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  31031. var intersectInfo = null;
  31032. var material = this.getMaterial();
  31033. if (!material) {
  31034. return null;
  31035. }
  31036. switch (material.fillMode) {
  31037. case BABYLON.Material.PointListDrawMode:
  31038. case BABYLON.Material.LineListDrawMode:
  31039. case BABYLON.Material.LineLoopDrawMode:
  31040. case BABYLON.Material.LineStripDrawMode:
  31041. case BABYLON.Material.TriangleFanDrawMode:
  31042. case BABYLON.Material.TriangleStripDrawMode:
  31043. return null;
  31044. }
  31045. // LineMesh first as it's also a Mesh...
  31046. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31047. var lineMesh = this._mesh;
  31048. // Line test
  31049. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31050. var p0 = positions[indices[index]];
  31051. var p1 = positions[indices[index + 1]];
  31052. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31053. if (length < 0) {
  31054. continue;
  31055. }
  31056. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31057. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31058. if (fastCheck) {
  31059. break;
  31060. }
  31061. }
  31062. }
  31063. }
  31064. else {
  31065. // Triangles test
  31066. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31067. var p0 = positions[indices[index]];
  31068. var p1 = positions[indices[index + 1]];
  31069. var p2 = positions[indices[index + 2]];
  31070. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31071. if (currentIntersectInfo) {
  31072. if (currentIntersectInfo.distance < 0) {
  31073. continue;
  31074. }
  31075. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31076. intersectInfo = currentIntersectInfo;
  31077. intersectInfo.faceId = index / 3;
  31078. if (fastCheck) {
  31079. break;
  31080. }
  31081. }
  31082. }
  31083. }
  31084. }
  31085. return intersectInfo;
  31086. };
  31087. SubMesh.prototype._rebuild = function () {
  31088. if (this._linesIndexBuffer) {
  31089. this._linesIndexBuffer = null;
  31090. }
  31091. };
  31092. // Clone
  31093. /**
  31094. * Creates a new Submesh from the passed Mesh.
  31095. */
  31096. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31097. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31098. if (!this.IsGlobal) {
  31099. var boundingInfo = this.getBoundingInfo();
  31100. if (!boundingInfo) {
  31101. return result;
  31102. }
  31103. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31104. }
  31105. return result;
  31106. };
  31107. // Dispose
  31108. /**
  31109. * Disposes the Submesh.
  31110. * Returns nothing.
  31111. */
  31112. SubMesh.prototype.dispose = function () {
  31113. if (this._linesIndexBuffer) {
  31114. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31115. this._linesIndexBuffer = null;
  31116. }
  31117. // Remove from mesh
  31118. var index = this._mesh.subMeshes.indexOf(this);
  31119. this._mesh.subMeshes.splice(index, 1);
  31120. };
  31121. // Statics
  31122. /**
  31123. * Creates a new Submesh from the passed parameters :
  31124. * - materialIndex (integer) : the index of the main mesh material.
  31125. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31126. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31127. * - mesh (Mesh) : the main mesh to create the submesh from.
  31128. * - renderingMesh (optional Mesh) : rendering mesh.
  31129. */
  31130. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31131. var minVertexIndex = Number.MAX_VALUE;
  31132. var maxVertexIndex = -Number.MAX_VALUE;
  31133. renderingMesh = (renderingMesh || mesh);
  31134. var indices = renderingMesh.getIndices();
  31135. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31136. var vertexIndex = indices[index];
  31137. if (vertexIndex < minVertexIndex)
  31138. minVertexIndex = vertexIndex;
  31139. if (vertexIndex > maxVertexIndex)
  31140. maxVertexIndex = vertexIndex;
  31141. }
  31142. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31143. };
  31144. return SubMesh;
  31145. }(BaseSubMesh));
  31146. BABYLON.SubMesh = SubMesh;
  31147. })(BABYLON || (BABYLON = {}));
  31148. //# sourceMappingURL=babylon.subMesh.js.map
  31149. "use strict";
  31150. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31151. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31152. s = arguments[i];
  31153. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31154. t[p] = s[p];
  31155. }
  31156. return t;
  31157. };
  31158. var BABYLON;
  31159. (function (BABYLON) {
  31160. /**
  31161. * Manages the defines for the Material.
  31162. */
  31163. var MaterialDefines = /** @class */ (function () {
  31164. function MaterialDefines() {
  31165. this._isDirty = true;
  31166. this._areLightsDirty = true;
  31167. this._areAttributesDirty = true;
  31168. this._areTexturesDirty = true;
  31169. this._areFresnelDirty = true;
  31170. this._areMiscDirty = true;
  31171. this._areImageProcessingDirty = true;
  31172. this._normals = false;
  31173. this._uvs = false;
  31174. this._needNormals = false;
  31175. this._needUVs = false;
  31176. }
  31177. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31178. /**
  31179. * Specifies if the material needs to be re-calculated.
  31180. */
  31181. get: function () {
  31182. return this._isDirty;
  31183. },
  31184. enumerable: true,
  31185. configurable: true
  31186. });
  31187. /**
  31188. * Marks the material to indicate that it has been re-calculated.
  31189. */
  31190. MaterialDefines.prototype.markAsProcessed = function () {
  31191. this._isDirty = false;
  31192. this._areAttributesDirty = false;
  31193. this._areTexturesDirty = false;
  31194. this._areFresnelDirty = false;
  31195. this._areLightsDirty = false;
  31196. this._areMiscDirty = false;
  31197. this._areImageProcessingDirty = false;
  31198. };
  31199. /**
  31200. * Marks the material to indicate that it needs to be re-calculated.
  31201. */
  31202. MaterialDefines.prototype.markAsUnprocessed = function () {
  31203. this._isDirty = true;
  31204. };
  31205. /**
  31206. * Marks the material to indicate all of its defines need to be re-calculated.
  31207. */
  31208. MaterialDefines.prototype.markAllAsDirty = function () {
  31209. this._areTexturesDirty = true;
  31210. this._areAttributesDirty = true;
  31211. this._areLightsDirty = true;
  31212. this._areFresnelDirty = true;
  31213. this._areMiscDirty = true;
  31214. this._areImageProcessingDirty = true;
  31215. this._isDirty = true;
  31216. };
  31217. /**
  31218. * Marks the material to indicate that image processing needs to be re-calculated.
  31219. */
  31220. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31221. this._areImageProcessingDirty = true;
  31222. this._isDirty = true;
  31223. };
  31224. /**
  31225. * Marks the material to indicate the lights need to be re-calculated.
  31226. */
  31227. MaterialDefines.prototype.markAsLightDirty = function () {
  31228. this._areLightsDirty = true;
  31229. this._isDirty = true;
  31230. };
  31231. /**
  31232. * Marks the attribute state as changed.
  31233. */
  31234. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31235. this._areAttributesDirty = true;
  31236. this._isDirty = true;
  31237. };
  31238. /**
  31239. * Marks the texture state as changed.
  31240. */
  31241. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31242. this._areTexturesDirty = true;
  31243. this._isDirty = true;
  31244. };
  31245. /**
  31246. * Marks the fresnel state as changed.
  31247. */
  31248. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31249. this._areFresnelDirty = true;
  31250. this._isDirty = true;
  31251. };
  31252. /**
  31253. * Marks the misc state as changed.
  31254. */
  31255. MaterialDefines.prototype.markAsMiscDirty = function () {
  31256. this._areMiscDirty = true;
  31257. this._isDirty = true;
  31258. };
  31259. /**
  31260. * Rebuilds the material defines.
  31261. */
  31262. MaterialDefines.prototype.rebuild = function () {
  31263. if (this._keys) {
  31264. delete this._keys;
  31265. }
  31266. this._keys = [];
  31267. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31268. var key = _a[_i];
  31269. if (key[0] === "_") {
  31270. continue;
  31271. }
  31272. this._keys.push(key);
  31273. }
  31274. };
  31275. /**
  31276. * Specifies if two material defines are equal.
  31277. * @param other - A material define instance to compare to.
  31278. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31279. */
  31280. MaterialDefines.prototype.isEqual = function (other) {
  31281. if (this._keys.length !== other._keys.length) {
  31282. return false;
  31283. }
  31284. for (var index = 0; index < this._keys.length; index++) {
  31285. var prop = this._keys[index];
  31286. if (this[prop] !== other[prop]) {
  31287. return false;
  31288. }
  31289. }
  31290. return true;
  31291. };
  31292. /**
  31293. * Clones this instance's defines to another instance.
  31294. * @param other - material defines to clone values to.
  31295. */
  31296. MaterialDefines.prototype.cloneTo = function (other) {
  31297. if (this._keys.length !== other._keys.length) {
  31298. other._keys = this._keys.slice(0);
  31299. }
  31300. for (var index = 0; index < this._keys.length; index++) {
  31301. var prop = this._keys[index];
  31302. other[prop] = this[prop];
  31303. }
  31304. };
  31305. /**
  31306. * Resets the material define values.
  31307. */
  31308. MaterialDefines.prototype.reset = function () {
  31309. for (var index = 0; index < this._keys.length; index++) {
  31310. var prop = this._keys[index];
  31311. var type = typeof this[prop];
  31312. switch (type) {
  31313. case "number":
  31314. this[prop] = 0;
  31315. break;
  31316. case "string":
  31317. this[prop] = "";
  31318. break;
  31319. default:
  31320. this[prop] = false;
  31321. break;
  31322. }
  31323. }
  31324. };
  31325. /**
  31326. * Converts the material define values to a string.
  31327. * @returns - String of material define information.
  31328. */
  31329. MaterialDefines.prototype.toString = function () {
  31330. var result = "";
  31331. for (var index = 0; index < this._keys.length; index++) {
  31332. var prop = this._keys[index];
  31333. var value = this[prop];
  31334. var type = typeof value;
  31335. switch (type) {
  31336. case "number":
  31337. case "string":
  31338. result += "#define " + prop + " " + value + "\n";
  31339. break;
  31340. default:
  31341. if (value) {
  31342. result += "#define " + prop + "\n";
  31343. }
  31344. break;
  31345. }
  31346. }
  31347. return result;
  31348. };
  31349. return MaterialDefines;
  31350. }());
  31351. BABYLON.MaterialDefines = MaterialDefines;
  31352. /**
  31353. * This offers the main features of a material in BJS.
  31354. */
  31355. var Material = /** @class */ (function () {
  31356. /**
  31357. * Creates a material instance.
  31358. * @param name - The name of the material.
  31359. * @param scene - The BJS scene to reference.
  31360. * @param doNotAdd - Specifies if the material should be added to the scene.
  31361. */
  31362. function Material(name, scene, doNotAdd) {
  31363. /**
  31364. * Specifies if the ready state should be checked on each call.
  31365. */
  31366. this.checkReadyOnEveryCall = false;
  31367. /**
  31368. * Specifies if the ready state should be checked once.
  31369. */
  31370. this.checkReadyOnlyOnce = false;
  31371. /**
  31372. * The state of the material.
  31373. */
  31374. this.state = "";
  31375. /**
  31376. * The alpha value of the material.
  31377. */
  31378. this._alpha = 1.0;
  31379. /**
  31380. * Specifies if back face culling is enabled.
  31381. */
  31382. this._backFaceCulling = true;
  31383. /**
  31384. * Specifies if the material should be serialized.
  31385. */
  31386. this.doNotSerialize = false;
  31387. /**
  31388. * Specifies if the effect should be stored on sub meshes.
  31389. */
  31390. this.storeEffectOnSubMeshes = false;
  31391. /**
  31392. * An event triggered when the material is disposed.
  31393. * @type {BABYLON.Observable}
  31394. */
  31395. this.onDisposeObservable = new BABYLON.Observable();
  31396. /**
  31397. * An event triggered when the material is bound.
  31398. * @type {BABYLON.Observable}
  31399. */
  31400. this.onBindObservable = new BABYLON.Observable();
  31401. /**
  31402. * An event triggered when the material is unbound.
  31403. * @type {BABYLON.Observable}
  31404. */
  31405. this.onUnBindObservable = new BABYLON.Observable();
  31406. /**
  31407. * Stores the value of the alpha mode.
  31408. */
  31409. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31410. /**
  31411. * Stores the state of the need depth pre-pass value.
  31412. */
  31413. this._needDepthPrePass = false;
  31414. /**
  31415. * Specifies if depth writing should be disabled.
  31416. */
  31417. this.disableDepthWrite = false;
  31418. /**
  31419. * Specifies if depth writing should be forced.
  31420. */
  31421. this.forceDepthWrite = false;
  31422. /**
  31423. * Specifies if there should be a separate pass for culling.
  31424. */
  31425. this.separateCullingPass = false;
  31426. /**
  31427. * Stores the state specifing if fog should be enabled.
  31428. */
  31429. this._fogEnabled = true;
  31430. /**
  31431. * Stores the size of points.
  31432. */
  31433. this.pointSize = 1.0;
  31434. /**
  31435. * Stores the z offset value.
  31436. */
  31437. this.zOffset = 0;
  31438. /**
  31439. * Specifies if the material was previously ready.
  31440. */
  31441. this._wasPreviouslyReady = false;
  31442. /**
  31443. * Stores the fill mode state.
  31444. */
  31445. this._fillMode = Material.TriangleFillMode;
  31446. this.name = name;
  31447. this.id = name || BABYLON.Tools.RandomId();
  31448. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31449. if (this._scene.useRightHandedSystem) {
  31450. this.sideOrientation = Material.ClockWiseSideOrientation;
  31451. }
  31452. else {
  31453. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31454. }
  31455. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31456. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31457. if (!doNotAdd) {
  31458. this._scene.materials.push(this);
  31459. }
  31460. }
  31461. Object.defineProperty(Material, "TriangleFillMode", {
  31462. /**
  31463. * Returns the triangle fill mode.
  31464. */
  31465. get: function () {
  31466. return Material._TriangleFillMode;
  31467. },
  31468. enumerable: true,
  31469. configurable: true
  31470. });
  31471. Object.defineProperty(Material, "WireFrameFillMode", {
  31472. /**
  31473. * Returns the wireframe mode.
  31474. */
  31475. get: function () {
  31476. return Material._WireFrameFillMode;
  31477. },
  31478. enumerable: true,
  31479. configurable: true
  31480. });
  31481. Object.defineProperty(Material, "PointFillMode", {
  31482. /**
  31483. * Returns the point fill mode.
  31484. */
  31485. get: function () {
  31486. return Material._PointFillMode;
  31487. },
  31488. enumerable: true,
  31489. configurable: true
  31490. });
  31491. Object.defineProperty(Material, "PointListDrawMode", {
  31492. /**
  31493. * Returns the point list draw mode.
  31494. */
  31495. get: function () {
  31496. return Material._PointListDrawMode;
  31497. },
  31498. enumerable: true,
  31499. configurable: true
  31500. });
  31501. Object.defineProperty(Material, "LineListDrawMode", {
  31502. /**
  31503. * Returns the line list draw mode.
  31504. */
  31505. get: function () {
  31506. return Material._LineListDrawMode;
  31507. },
  31508. enumerable: true,
  31509. configurable: true
  31510. });
  31511. Object.defineProperty(Material, "LineLoopDrawMode", {
  31512. /**
  31513. * Returns the line loop draw mode.
  31514. */
  31515. get: function () {
  31516. return Material._LineLoopDrawMode;
  31517. },
  31518. enumerable: true,
  31519. configurable: true
  31520. });
  31521. Object.defineProperty(Material, "LineStripDrawMode", {
  31522. /**
  31523. * Returns the line strip draw mode.
  31524. */
  31525. get: function () {
  31526. return Material._LineStripDrawMode;
  31527. },
  31528. enumerable: true,
  31529. configurable: true
  31530. });
  31531. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31532. /**
  31533. * Returns the triangle strip draw mode.
  31534. */
  31535. get: function () {
  31536. return Material._TriangleStripDrawMode;
  31537. },
  31538. enumerable: true,
  31539. configurable: true
  31540. });
  31541. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31542. /**
  31543. * Returns the triangle fan draw mode.
  31544. */
  31545. get: function () {
  31546. return Material._TriangleFanDrawMode;
  31547. },
  31548. enumerable: true,
  31549. configurable: true
  31550. });
  31551. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31552. /**
  31553. * Returns the clock-wise side orientation.
  31554. */
  31555. get: function () {
  31556. return Material._ClockWiseSideOrientation;
  31557. },
  31558. enumerable: true,
  31559. configurable: true
  31560. });
  31561. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31562. /**
  31563. * Returns the counter clock-wise side orientation.
  31564. */
  31565. get: function () {
  31566. return Material._CounterClockWiseSideOrientation;
  31567. },
  31568. enumerable: true,
  31569. configurable: true
  31570. });
  31571. Object.defineProperty(Material, "TextureDirtyFlag", {
  31572. /**
  31573. * Returns the dirty texture flag value.
  31574. */
  31575. get: function () {
  31576. return Material._TextureDirtyFlag;
  31577. },
  31578. enumerable: true,
  31579. configurable: true
  31580. });
  31581. Object.defineProperty(Material, "LightDirtyFlag", {
  31582. /**
  31583. * Returns the dirty light flag value.
  31584. */
  31585. get: function () {
  31586. return Material._LightDirtyFlag;
  31587. },
  31588. enumerable: true,
  31589. configurable: true
  31590. });
  31591. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31592. /**
  31593. * Returns the dirty fresnel flag value.
  31594. */
  31595. get: function () {
  31596. return Material._FresnelDirtyFlag;
  31597. },
  31598. enumerable: true,
  31599. configurable: true
  31600. });
  31601. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31602. /**
  31603. * Returns the dirty attributes flag value.
  31604. */
  31605. get: function () {
  31606. return Material._AttributesDirtyFlag;
  31607. },
  31608. enumerable: true,
  31609. configurable: true
  31610. });
  31611. Object.defineProperty(Material, "MiscDirtyFlag", {
  31612. /**
  31613. * Returns the dirty misc flag value.
  31614. */
  31615. get: function () {
  31616. return Material._MiscDirtyFlag;
  31617. },
  31618. enumerable: true,
  31619. configurable: true
  31620. });
  31621. Object.defineProperty(Material.prototype, "alpha", {
  31622. /**
  31623. * Gets the alpha value of the material.
  31624. */
  31625. get: function () {
  31626. return this._alpha;
  31627. },
  31628. /**
  31629. * Sets the alpha value of the material.
  31630. */
  31631. set: function (value) {
  31632. if (this._alpha === value) {
  31633. return;
  31634. }
  31635. this._alpha = value;
  31636. this.markAsDirty(Material.MiscDirtyFlag);
  31637. },
  31638. enumerable: true,
  31639. configurable: true
  31640. });
  31641. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31642. /**
  31643. * Gets the back-face culling state.
  31644. */
  31645. get: function () {
  31646. return this._backFaceCulling;
  31647. },
  31648. /**
  31649. * Sets the back-face culling state.
  31650. */
  31651. set: function (value) {
  31652. if (this._backFaceCulling === value) {
  31653. return;
  31654. }
  31655. this._backFaceCulling = value;
  31656. this.markAsDirty(Material.TextureDirtyFlag);
  31657. },
  31658. enumerable: true,
  31659. configurable: true
  31660. });
  31661. Object.defineProperty(Material.prototype, "onDispose", {
  31662. /**
  31663. * Called during a dispose event.
  31664. */
  31665. set: function (callback) {
  31666. if (this._onDisposeObserver) {
  31667. this.onDisposeObservable.remove(this._onDisposeObserver);
  31668. }
  31669. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31670. },
  31671. enumerable: true,
  31672. configurable: true
  31673. });
  31674. Object.defineProperty(Material.prototype, "onBind", {
  31675. /**
  31676. * Called during a bind event.
  31677. */
  31678. set: function (callback) {
  31679. if (this._onBindObserver) {
  31680. this.onBindObservable.remove(this._onBindObserver);
  31681. }
  31682. this._onBindObserver = this.onBindObservable.add(callback);
  31683. },
  31684. enumerable: true,
  31685. configurable: true
  31686. });
  31687. Object.defineProperty(Material.prototype, "alphaMode", {
  31688. /**
  31689. * Gets the value of the alpha mode.
  31690. */
  31691. get: function () {
  31692. return this._alphaMode;
  31693. },
  31694. /**
  31695. * Sets the value of the alpha mode.
  31696. */
  31697. set: function (value) {
  31698. if (this._alphaMode === value) {
  31699. return;
  31700. }
  31701. this._alphaMode = value;
  31702. this.markAsDirty(Material.TextureDirtyFlag);
  31703. },
  31704. enumerable: true,
  31705. configurable: true
  31706. });
  31707. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31708. /**
  31709. * Gets the depth pre-pass value.
  31710. */
  31711. get: function () {
  31712. return this._needDepthPrePass;
  31713. },
  31714. /**
  31715. * Sets the need depth pre-pass value.
  31716. */
  31717. set: function (value) {
  31718. if (this._needDepthPrePass === value) {
  31719. return;
  31720. }
  31721. this._needDepthPrePass = value;
  31722. if (this._needDepthPrePass) {
  31723. this.checkReadyOnEveryCall = true;
  31724. }
  31725. },
  31726. enumerable: true,
  31727. configurable: true
  31728. });
  31729. Object.defineProperty(Material.prototype, "fogEnabled", {
  31730. /**
  31731. * Gets the value of the fog enabled state.
  31732. */
  31733. get: function () {
  31734. return this._fogEnabled;
  31735. },
  31736. /**
  31737. * Sets the state for enabling fog.
  31738. */
  31739. set: function (value) {
  31740. if (this._fogEnabled === value) {
  31741. return;
  31742. }
  31743. this._fogEnabled = value;
  31744. this.markAsDirty(Material.MiscDirtyFlag);
  31745. },
  31746. enumerable: true,
  31747. configurable: true
  31748. });
  31749. Object.defineProperty(Material.prototype, "wireframe", {
  31750. /**
  31751. * Gets a value specifying if wireframe mode is enabled.
  31752. */
  31753. get: function () {
  31754. switch (this._fillMode) {
  31755. case Material.WireFrameFillMode:
  31756. case Material.LineListDrawMode:
  31757. case Material.LineLoopDrawMode:
  31758. case Material.LineStripDrawMode:
  31759. return true;
  31760. }
  31761. return this._scene.forceWireframe;
  31762. },
  31763. /**
  31764. * Sets the state of wireframe mode.
  31765. */
  31766. set: function (value) {
  31767. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31768. },
  31769. enumerable: true,
  31770. configurable: true
  31771. });
  31772. Object.defineProperty(Material.prototype, "pointsCloud", {
  31773. /**
  31774. * Gets the value specifying if point clouds are enabled.
  31775. */
  31776. get: function () {
  31777. switch (this._fillMode) {
  31778. case Material.PointFillMode:
  31779. case Material.PointListDrawMode:
  31780. return true;
  31781. }
  31782. return this._scene.forcePointsCloud;
  31783. },
  31784. /**
  31785. * Sets the state of point cloud mode.
  31786. */
  31787. set: function (value) {
  31788. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31789. },
  31790. enumerable: true,
  31791. configurable: true
  31792. });
  31793. Object.defineProperty(Material.prototype, "fillMode", {
  31794. /**
  31795. * Gets the material fill mode.
  31796. */
  31797. get: function () {
  31798. return this._fillMode;
  31799. },
  31800. /**
  31801. * Sets the material fill mode.
  31802. */
  31803. set: function (value) {
  31804. if (this._fillMode === value) {
  31805. return;
  31806. }
  31807. this._fillMode = value;
  31808. this.markAsDirty(Material.MiscDirtyFlag);
  31809. },
  31810. enumerable: true,
  31811. configurable: true
  31812. });
  31813. /**
  31814. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31815. * subclasses should override adding information pertainent to themselves.
  31816. * @returns - String with material information.
  31817. */
  31818. Material.prototype.toString = function (fullDetails) {
  31819. var ret = "Name: " + this.name;
  31820. if (fullDetails) {
  31821. }
  31822. return ret;
  31823. };
  31824. /**
  31825. * Gets the class name of the material.
  31826. * @returns - String with the class name of the material.
  31827. */
  31828. Material.prototype.getClassName = function () {
  31829. return "Material";
  31830. };
  31831. Object.defineProperty(Material.prototype, "isFrozen", {
  31832. /**
  31833. * Specifies if updates for the material been locked.
  31834. */
  31835. get: function () {
  31836. return this.checkReadyOnlyOnce;
  31837. },
  31838. enumerable: true,
  31839. configurable: true
  31840. });
  31841. /**
  31842. * Locks updates for the material.
  31843. */
  31844. Material.prototype.freeze = function () {
  31845. this.checkReadyOnlyOnce = true;
  31846. };
  31847. /**
  31848. * Unlocks updates for the material.
  31849. */
  31850. Material.prototype.unfreeze = function () {
  31851. this.checkReadyOnlyOnce = false;
  31852. };
  31853. /**
  31854. * Specifies if the material is ready to be used.
  31855. * @param mesh - BJS mesh.
  31856. * @param useInstances - Specifies if instances should be used.
  31857. * @returns - Boolean indicating if the material is ready to be used.
  31858. */
  31859. Material.prototype.isReady = function (mesh, useInstances) {
  31860. return true;
  31861. };
  31862. /**
  31863. * Specifies that the submesh is ready to be used.
  31864. * @param mesh - BJS mesh.
  31865. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31866. * @param useInstances - Specifies that instances should be used.
  31867. * @returns - boolean indicating that the submesh is ready or not.
  31868. */
  31869. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31870. return false;
  31871. };
  31872. /**
  31873. * Returns the material effect.
  31874. * @returns - Nullable material effect.
  31875. */
  31876. Material.prototype.getEffect = function () {
  31877. return this._effect;
  31878. };
  31879. /**
  31880. * Returns the BJS scene.
  31881. * @returns - BJS Scene.
  31882. */
  31883. Material.prototype.getScene = function () {
  31884. return this._scene;
  31885. };
  31886. /**
  31887. * Specifies if the material will require alpha blending
  31888. * @returns - Boolean specifying if alpha blending is needed.
  31889. */
  31890. Material.prototype.needAlphaBlending = function () {
  31891. return (this.alpha < 1.0);
  31892. };
  31893. /**
  31894. * Specifies if the mesh will require alpha blending.
  31895. * @param mesh - BJS mesh.
  31896. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31897. */
  31898. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31899. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31900. };
  31901. /**
  31902. * Specifies if this material should be rendered in alpha test mode.
  31903. * @returns - Boolean specifying if an alpha test is needed.
  31904. */
  31905. Material.prototype.needAlphaTesting = function () {
  31906. return false;
  31907. };
  31908. /**
  31909. * Gets the texture used for the alpha test.
  31910. * @returns - Nullable alpha test texture.
  31911. */
  31912. Material.prototype.getAlphaTestTexture = function () {
  31913. return null;
  31914. };
  31915. /**
  31916. * Marks the material to indicate that it needs to be re-calculated.
  31917. */
  31918. Material.prototype.markDirty = function () {
  31919. this._wasPreviouslyReady = false;
  31920. };
  31921. Material.prototype._preBind = function (effect, overrideOrientation) {
  31922. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31923. var engine = this._scene.getEngine();
  31924. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31925. var reverse = orientation === Material.ClockWiseSideOrientation;
  31926. engine.enableEffect(effect ? effect : this._effect);
  31927. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31928. return reverse;
  31929. };
  31930. /**
  31931. * Binds the material to the mesh.
  31932. * @param world - World transformation matrix.
  31933. * @param mesh - Mesh to bind the material to.
  31934. */
  31935. Material.prototype.bind = function (world, mesh) {
  31936. };
  31937. /**
  31938. * Binds the submesh to the material.
  31939. * @param world - World transformation matrix.
  31940. * @param mesh - Mesh containing the submesh.
  31941. * @param subMesh - Submesh to bind the material to.
  31942. */
  31943. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31944. };
  31945. /**
  31946. * Binds the world matrix to the material.
  31947. * @param world - World transformation matrix.
  31948. */
  31949. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31950. };
  31951. /**
  31952. * Binds the scene's uniform buffer to the effect.
  31953. * @param effect - Effect to bind to the scene uniform buffer.
  31954. * @param sceneUbo - Scene uniform buffer.
  31955. */
  31956. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31957. sceneUbo.bindToEffect(effect, "Scene");
  31958. };
  31959. /**
  31960. * Binds the view matrix to the effect.
  31961. * @param effect - Effect to bind the view matrix to.
  31962. */
  31963. Material.prototype.bindView = function (effect) {
  31964. if (!this._useUBO) {
  31965. effect.setMatrix("view", this.getScene().getViewMatrix());
  31966. }
  31967. else {
  31968. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31969. }
  31970. };
  31971. /**
  31972. * Binds the view projection matrix to the effect.
  31973. * @param effect - Effect to bind the view projection matrix to.
  31974. */
  31975. Material.prototype.bindViewProjection = function (effect) {
  31976. if (!this._useUBO) {
  31977. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31978. }
  31979. else {
  31980. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31981. }
  31982. };
  31983. /**
  31984. * Specifies if material alpha testing should be turned on for the mesh.
  31985. * @param mesh - BJS mesh.
  31986. */
  31987. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31988. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31989. };
  31990. /**
  31991. * Processes to execute after binding the material to a mesh.
  31992. * @param mesh - BJS mesh.
  31993. */
  31994. Material.prototype._afterBind = function (mesh) {
  31995. this._scene._cachedMaterial = this;
  31996. if (mesh) {
  31997. this._scene._cachedVisibility = mesh.visibility;
  31998. }
  31999. else {
  32000. this._scene._cachedVisibility = 1;
  32001. }
  32002. if (mesh) {
  32003. this.onBindObservable.notifyObservers(mesh);
  32004. }
  32005. if (this.disableDepthWrite) {
  32006. var engine = this._scene.getEngine();
  32007. this._cachedDepthWriteState = engine.getDepthWrite();
  32008. engine.setDepthWrite(false);
  32009. }
  32010. };
  32011. /**
  32012. * Unbinds the material from the mesh.
  32013. */
  32014. Material.prototype.unbind = function () {
  32015. this.onUnBindObservable.notifyObservers(this);
  32016. if (this.disableDepthWrite) {
  32017. var engine = this._scene.getEngine();
  32018. engine.setDepthWrite(this._cachedDepthWriteState);
  32019. }
  32020. };
  32021. /**
  32022. * Gets the active textures from the material.
  32023. * @returns - Array of textures.
  32024. */
  32025. Material.prototype.getActiveTextures = function () {
  32026. return [];
  32027. };
  32028. /**
  32029. * Specifies if the material uses a texture.
  32030. * @param texture - Texture to check against the material.
  32031. * @returns - Boolean specifying if the material uses the texture.
  32032. */
  32033. Material.prototype.hasTexture = function (texture) {
  32034. return false;
  32035. };
  32036. /**
  32037. * Makes a duplicate of the material, and gives it a new name.
  32038. * @param name - Name to call the duplicated material.
  32039. * @returns - Nullable cloned material
  32040. */
  32041. Material.prototype.clone = function (name) {
  32042. return null;
  32043. };
  32044. /**
  32045. * Gets the meshes bound to the material.
  32046. * @returns - Array of meshes bound to the material.
  32047. */
  32048. Material.prototype.getBindedMeshes = function () {
  32049. var result = new Array();
  32050. for (var index = 0; index < this._scene.meshes.length; index++) {
  32051. var mesh = this._scene.meshes[index];
  32052. if (mesh.material === this) {
  32053. result.push(mesh);
  32054. }
  32055. }
  32056. return result;
  32057. };
  32058. /**
  32059. * Force shader compilation
  32060. * @param mesh - BJS mesh.
  32061. * @param onCompiled - function to execute once the material is compiled.
  32062. * @param options - options to pass to this function.
  32063. */
  32064. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32065. var _this = this;
  32066. var localOptions = __assign({ clipPlane: false }, options);
  32067. var subMesh = new BABYLON.BaseSubMesh();
  32068. var scene = this.getScene();
  32069. var checkReady = function () {
  32070. if (!_this._scene || !_this._scene.getEngine()) {
  32071. return;
  32072. }
  32073. if (subMesh._materialDefines) {
  32074. subMesh._materialDefines._renderId = -1;
  32075. }
  32076. var clipPlaneState = scene.clipPlane;
  32077. if (localOptions.clipPlane) {
  32078. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32079. }
  32080. if (_this.storeEffectOnSubMeshes) {
  32081. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32082. if (onCompiled) {
  32083. onCompiled(_this);
  32084. }
  32085. }
  32086. else {
  32087. setTimeout(checkReady, 16);
  32088. }
  32089. }
  32090. else {
  32091. if (_this.isReady(mesh)) {
  32092. if (onCompiled) {
  32093. onCompiled(_this);
  32094. }
  32095. }
  32096. else {
  32097. setTimeout(checkReady, 16);
  32098. }
  32099. }
  32100. if (localOptions.clipPlane) {
  32101. scene.clipPlane = clipPlaneState;
  32102. }
  32103. };
  32104. checkReady();
  32105. };
  32106. /**
  32107. * Force shader compilation.
  32108. * @param mesh The mesh that will use this material
  32109. * @param options Additional options for compiling the shaders
  32110. * @returns A promise that resolves when the compilation completes
  32111. */
  32112. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32113. var _this = this;
  32114. return new Promise(function (resolve) {
  32115. _this.forceCompilation(mesh, function () {
  32116. resolve();
  32117. }, options);
  32118. });
  32119. };
  32120. /**
  32121. * Marks a define in the material to indicate that it needs to be re-computed.
  32122. * @param flag - Material define flag.
  32123. */
  32124. Material.prototype.markAsDirty = function (flag) {
  32125. if (flag & Material.TextureDirtyFlag) {
  32126. this._markAllSubMeshesAsTexturesDirty();
  32127. }
  32128. if (flag & Material.LightDirtyFlag) {
  32129. this._markAllSubMeshesAsLightsDirty();
  32130. }
  32131. if (flag & Material.FresnelDirtyFlag) {
  32132. this._markAllSubMeshesAsFresnelDirty();
  32133. }
  32134. if (flag & Material.AttributesDirtyFlag) {
  32135. this._markAllSubMeshesAsAttributesDirty();
  32136. }
  32137. if (flag & Material.MiscDirtyFlag) {
  32138. this._markAllSubMeshesAsMiscDirty();
  32139. }
  32140. this.getScene().resetCachedMaterial();
  32141. };
  32142. /**
  32143. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32144. * @param func - function which checks material defines against the submeshes.
  32145. */
  32146. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32147. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32148. var mesh = _a[_i];
  32149. if (!mesh.subMeshes) {
  32150. continue;
  32151. }
  32152. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32153. var subMesh = _c[_b];
  32154. if (subMesh.getMaterial() !== this) {
  32155. continue;
  32156. }
  32157. if (!subMesh._materialDefines) {
  32158. continue;
  32159. }
  32160. func(subMesh._materialDefines);
  32161. }
  32162. }
  32163. };
  32164. /**
  32165. * Indicates that image processing needs to be re-calculated for all submeshes.
  32166. */
  32167. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32168. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32169. };
  32170. /**
  32171. * Indicates that textures need to be re-calculated for all submeshes.
  32172. */
  32173. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32174. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32175. };
  32176. /**
  32177. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32178. */
  32179. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32180. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32181. };
  32182. /**
  32183. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32184. */
  32185. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32186. this._markAllSubMeshesAsDirty(function (defines) {
  32187. defines.markAsFresnelDirty();
  32188. defines.markAsMiscDirty();
  32189. });
  32190. };
  32191. /**
  32192. * Indicates that lights need to be re-calculated for all submeshes.
  32193. */
  32194. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32195. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32196. };
  32197. /**
  32198. * Indicates that attributes need to be re-calculated for all submeshes.
  32199. */
  32200. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32201. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32202. };
  32203. /**
  32204. * Indicates that misc needs to be re-calculated for all submeshes.
  32205. */
  32206. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32207. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32208. };
  32209. /**
  32210. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32211. */
  32212. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32213. this._markAllSubMeshesAsDirty(function (defines) {
  32214. defines.markAsTexturesDirty();
  32215. defines.markAsMiscDirty();
  32216. });
  32217. };
  32218. /**
  32219. * Disposes the material.
  32220. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32221. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32222. */
  32223. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32224. // Animations
  32225. this.getScene().stopAnimation(this);
  32226. this.getScene().freeProcessedMaterials();
  32227. // Remove from scene
  32228. var index = this._scene.materials.indexOf(this);
  32229. if (index >= 0) {
  32230. this._scene.materials.splice(index, 1);
  32231. }
  32232. // Remove from meshes
  32233. for (index = 0; index < this._scene.meshes.length; index++) {
  32234. var mesh = this._scene.meshes[index];
  32235. if (mesh.material === this) {
  32236. mesh.material = null;
  32237. if (mesh.geometry) {
  32238. var geometry = (mesh.geometry);
  32239. if (this.storeEffectOnSubMeshes) {
  32240. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32241. var subMesh = _a[_i];
  32242. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32243. if (forceDisposeEffect && subMesh._materialEffect) {
  32244. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32245. }
  32246. }
  32247. }
  32248. else {
  32249. geometry._releaseVertexArrayObject(this._effect);
  32250. }
  32251. }
  32252. }
  32253. }
  32254. this._uniformBuffer.dispose();
  32255. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32256. if (forceDisposeEffect && this._effect) {
  32257. if (!this.storeEffectOnSubMeshes) {
  32258. this._scene.getEngine()._releaseEffect(this._effect);
  32259. }
  32260. this._effect = null;
  32261. }
  32262. // Callback
  32263. this.onDisposeObservable.notifyObservers(this);
  32264. this.onDisposeObservable.clear();
  32265. this.onBindObservable.clear();
  32266. this.onUnBindObservable.clear();
  32267. };
  32268. /**
  32269. * Serializes this material.
  32270. * @returns - serialized material object.
  32271. */
  32272. Material.prototype.serialize = function () {
  32273. return BABYLON.SerializationHelper.Serialize(this);
  32274. };
  32275. /**
  32276. * Creates a MultiMaterial from parse MultiMaterial data.
  32277. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32278. * @param scene - BJS scene.
  32279. * @returns - MultiMaterial.
  32280. */
  32281. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32282. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32283. multiMaterial.id = parsedMultiMaterial.id;
  32284. if (BABYLON.Tags) {
  32285. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32286. }
  32287. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32288. var subMatId = parsedMultiMaterial.materials[matIndex];
  32289. if (subMatId) {
  32290. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32291. }
  32292. else {
  32293. multiMaterial.subMaterials.push(null);
  32294. }
  32295. }
  32296. return multiMaterial;
  32297. };
  32298. /**
  32299. * Creates a material from parsed material data.
  32300. * @param parsedMaterial - Parsed material data.
  32301. * @param scene - BJS scene.
  32302. * @param rootUrl - Root URL containing the material information.
  32303. * @returns - Parsed material.
  32304. */
  32305. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32306. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32307. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32308. }
  32309. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32310. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32311. if (!BABYLON.LegacyPBRMaterial) {
  32312. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32313. return;
  32314. }
  32315. }
  32316. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32317. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32318. ;
  32319. };
  32320. // Triangle views
  32321. Material._TriangleFillMode = 0;
  32322. Material._WireFrameFillMode = 1;
  32323. Material._PointFillMode = 2;
  32324. // Draw modes
  32325. Material._PointListDrawMode = 3;
  32326. Material._LineListDrawMode = 4;
  32327. Material._LineLoopDrawMode = 5;
  32328. Material._LineStripDrawMode = 6;
  32329. Material._TriangleStripDrawMode = 7;
  32330. Material._TriangleFanDrawMode = 8;
  32331. /**
  32332. * Stores the clock-wise side orientation.
  32333. */
  32334. Material._ClockWiseSideOrientation = 0;
  32335. /**
  32336. * Stores the counter clock-wise side orientation.
  32337. */
  32338. Material._CounterClockWiseSideOrientation = 1;
  32339. /**
  32340. * The dirty texture flag value.
  32341. */
  32342. Material._TextureDirtyFlag = 1;
  32343. /**
  32344. * The dirty light flag value.
  32345. */
  32346. Material._LightDirtyFlag = 2;
  32347. /**
  32348. * The dirty fresnel flag value.
  32349. */
  32350. Material._FresnelDirtyFlag = 4;
  32351. /**
  32352. * The dirty attribute flag value.
  32353. */
  32354. Material._AttributesDirtyFlag = 8;
  32355. /**
  32356. * The dirty misc flag value.
  32357. */
  32358. Material._MiscDirtyFlag = 16;
  32359. __decorate([
  32360. BABYLON.serialize()
  32361. ], Material.prototype, "id", void 0);
  32362. __decorate([
  32363. BABYLON.serialize()
  32364. ], Material.prototype, "name", void 0);
  32365. __decorate([
  32366. BABYLON.serialize()
  32367. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32368. __decorate([
  32369. BABYLON.serialize()
  32370. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32371. __decorate([
  32372. BABYLON.serialize()
  32373. ], Material.prototype, "state", void 0);
  32374. __decorate([
  32375. BABYLON.serialize("alpha")
  32376. ], Material.prototype, "_alpha", void 0);
  32377. __decorate([
  32378. BABYLON.serialize("backFaceCulling")
  32379. ], Material.prototype, "_backFaceCulling", void 0);
  32380. __decorate([
  32381. BABYLON.serialize()
  32382. ], Material.prototype, "sideOrientation", void 0);
  32383. __decorate([
  32384. BABYLON.serialize("alphaMode")
  32385. ], Material.prototype, "_alphaMode", void 0);
  32386. __decorate([
  32387. BABYLON.serialize()
  32388. ], Material.prototype, "_needDepthPrePass", void 0);
  32389. __decorate([
  32390. BABYLON.serialize()
  32391. ], Material.prototype, "disableDepthWrite", void 0);
  32392. __decorate([
  32393. BABYLON.serialize()
  32394. ], Material.prototype, "forceDepthWrite", void 0);
  32395. __decorate([
  32396. BABYLON.serialize()
  32397. ], Material.prototype, "separateCullingPass", void 0);
  32398. __decorate([
  32399. BABYLON.serialize("fogEnabled")
  32400. ], Material.prototype, "_fogEnabled", void 0);
  32401. __decorate([
  32402. BABYLON.serialize()
  32403. ], Material.prototype, "pointSize", void 0);
  32404. __decorate([
  32405. BABYLON.serialize()
  32406. ], Material.prototype, "zOffset", void 0);
  32407. __decorate([
  32408. BABYLON.serialize()
  32409. ], Material.prototype, "wireframe", null);
  32410. __decorate([
  32411. BABYLON.serialize()
  32412. ], Material.prototype, "pointsCloud", null);
  32413. __decorate([
  32414. BABYLON.serialize()
  32415. ], Material.prototype, "fillMode", null);
  32416. return Material;
  32417. }());
  32418. BABYLON.Material = Material;
  32419. })(BABYLON || (BABYLON = {}));
  32420. //# sourceMappingURL=babylon.material.js.map
  32421. "use strict";
  32422. var BABYLON;
  32423. (function (BABYLON) {
  32424. var UniformBuffer = /** @class */ (function () {
  32425. /**
  32426. * Uniform buffer objects.
  32427. *
  32428. * Handles blocks of uniform on the GPU.
  32429. *
  32430. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32431. *
  32432. * For more information, please refer to :
  32433. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32434. */
  32435. function UniformBuffer(engine, data, dynamic) {
  32436. this._engine = engine;
  32437. this._noUBO = !engine.supportsUniformBuffers;
  32438. this._dynamic = dynamic;
  32439. this._data = data || [];
  32440. this._uniformLocations = {};
  32441. this._uniformSizes = {};
  32442. this._uniformLocationPointer = 0;
  32443. this._needSync = false;
  32444. if (this._noUBO) {
  32445. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32446. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32447. this.updateFloat = this._updateFloatForEffect;
  32448. this.updateFloat2 = this._updateFloat2ForEffect;
  32449. this.updateFloat3 = this._updateFloat3ForEffect;
  32450. this.updateFloat4 = this._updateFloat4ForEffect;
  32451. this.updateMatrix = this._updateMatrixForEffect;
  32452. this.updateVector3 = this._updateVector3ForEffect;
  32453. this.updateVector4 = this._updateVector4ForEffect;
  32454. this.updateColor3 = this._updateColor3ForEffect;
  32455. this.updateColor4 = this._updateColor4ForEffect;
  32456. }
  32457. else {
  32458. this._engine._uniformBuffers.push(this);
  32459. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32460. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32461. this.updateFloat = this._updateFloatForUniform;
  32462. this.updateFloat2 = this._updateFloat2ForUniform;
  32463. this.updateFloat3 = this._updateFloat3ForUniform;
  32464. this.updateFloat4 = this._updateFloat4ForUniform;
  32465. this.updateMatrix = this._updateMatrixForUniform;
  32466. this.updateVector3 = this._updateVector3ForUniform;
  32467. this.updateVector4 = this._updateVector4ForUniform;
  32468. this.updateColor3 = this._updateColor3ForUniform;
  32469. this.updateColor4 = this._updateColor4ForUniform;
  32470. }
  32471. }
  32472. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32473. // Properties
  32474. /**
  32475. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32476. * or just falling back on setUniformXXX calls.
  32477. */
  32478. get: function () {
  32479. return !this._noUBO;
  32480. },
  32481. enumerable: true,
  32482. configurable: true
  32483. });
  32484. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32485. /**
  32486. * Indicates if the WebGL underlying uniform buffer is in sync
  32487. * with the javascript cache data.
  32488. */
  32489. get: function () {
  32490. return !this._needSync;
  32491. },
  32492. enumerable: true,
  32493. configurable: true
  32494. });
  32495. /**
  32496. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32497. * Also, a dynamic UniformBuffer will disable cache verification and always
  32498. * update the underlying WebGL uniform buffer to the GPU.
  32499. */
  32500. UniformBuffer.prototype.isDynamic = function () {
  32501. return this._dynamic !== undefined;
  32502. };
  32503. /**
  32504. * The data cache on JS side.
  32505. */
  32506. UniformBuffer.prototype.getData = function () {
  32507. return this._bufferData;
  32508. };
  32509. /**
  32510. * The underlying WebGL Uniform buffer.
  32511. */
  32512. UniformBuffer.prototype.getBuffer = function () {
  32513. return this._buffer;
  32514. };
  32515. /**
  32516. * std140 layout specifies how to align data within an UBO structure.
  32517. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32518. * for specs.
  32519. */
  32520. UniformBuffer.prototype._fillAlignment = function (size) {
  32521. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32522. // and 4x4 matrices
  32523. // TODO : change if other types are used
  32524. var alignment;
  32525. if (size <= 2) {
  32526. alignment = size;
  32527. }
  32528. else {
  32529. alignment = 4;
  32530. }
  32531. if ((this._uniformLocationPointer % alignment) !== 0) {
  32532. var oldPointer = this._uniformLocationPointer;
  32533. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32534. var diff = this._uniformLocationPointer - oldPointer;
  32535. for (var i = 0; i < diff; i++) {
  32536. this._data.push(0);
  32537. }
  32538. }
  32539. };
  32540. /**
  32541. * Adds an uniform in the buffer.
  32542. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32543. * for the layout to be correct !
  32544. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32545. * @param {number|number[]} size Data size, or data directly.
  32546. */
  32547. UniformBuffer.prototype.addUniform = function (name, size) {
  32548. if (this._noUBO) {
  32549. return;
  32550. }
  32551. if (this._uniformLocations[name] !== undefined) {
  32552. // Already existing uniform
  32553. return;
  32554. }
  32555. // This function must be called in the order of the shader layout !
  32556. // size can be the size of the uniform, or data directly
  32557. var data;
  32558. if (size instanceof Array) {
  32559. data = size;
  32560. size = data.length;
  32561. }
  32562. else {
  32563. size = size;
  32564. data = [];
  32565. // Fill with zeros
  32566. for (var i = 0; i < size; i++) {
  32567. data.push(0);
  32568. }
  32569. }
  32570. this._fillAlignment(size);
  32571. this._uniformSizes[name] = size;
  32572. this._uniformLocations[name] = this._uniformLocationPointer;
  32573. this._uniformLocationPointer += size;
  32574. for (var i = 0; i < size; i++) {
  32575. this._data.push(data[i]);
  32576. }
  32577. this._needSync = true;
  32578. };
  32579. /**
  32580. * Wrapper for addUniform.
  32581. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32582. * @param {Matrix} mat A 4x4 matrix.
  32583. */
  32584. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32585. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32586. };
  32587. /**
  32588. * Wrapper for addUniform.
  32589. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32590. * @param {number} x
  32591. * @param {number} y
  32592. */
  32593. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32594. var temp = [x, y];
  32595. this.addUniform(name, temp);
  32596. };
  32597. /**
  32598. * Wrapper for addUniform.
  32599. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32600. * @param {number} x
  32601. * @param {number} y
  32602. * @param {number} z
  32603. */
  32604. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32605. var temp = [x, y, z];
  32606. this.addUniform(name, temp);
  32607. };
  32608. /**
  32609. * Wrapper for addUniform.
  32610. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32611. * @param {Color3} color
  32612. */
  32613. UniformBuffer.prototype.addColor3 = function (name, color) {
  32614. var temp = new Array();
  32615. color.toArray(temp);
  32616. this.addUniform(name, temp);
  32617. };
  32618. /**
  32619. * Wrapper for addUniform.
  32620. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32621. * @param {Color3} color
  32622. * @param {number} alpha
  32623. */
  32624. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32625. var temp = new Array();
  32626. color.toArray(temp);
  32627. temp.push(alpha);
  32628. this.addUniform(name, temp);
  32629. };
  32630. /**
  32631. * Wrapper for addUniform.
  32632. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32633. * @param {Vector3} vector
  32634. */
  32635. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32636. var temp = new Array();
  32637. vector.toArray(temp);
  32638. this.addUniform(name, temp);
  32639. };
  32640. /**
  32641. * Wrapper for addUniform.
  32642. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32643. */
  32644. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32645. this.addUniform(name, 12);
  32646. };
  32647. /**
  32648. * Wrapper for addUniform.
  32649. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32650. */
  32651. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32652. this.addUniform(name, 8);
  32653. };
  32654. /**
  32655. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32656. */
  32657. UniformBuffer.prototype.create = function () {
  32658. if (this._noUBO) {
  32659. return;
  32660. }
  32661. if (this._buffer) {
  32662. return; // nothing to do
  32663. }
  32664. // See spec, alignment must be filled as a vec4
  32665. this._fillAlignment(4);
  32666. this._bufferData = new Float32Array(this._data);
  32667. this._rebuild();
  32668. this._needSync = true;
  32669. };
  32670. UniformBuffer.prototype._rebuild = function () {
  32671. if (this._noUBO) {
  32672. return;
  32673. }
  32674. if (this._dynamic) {
  32675. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32676. }
  32677. else {
  32678. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32679. }
  32680. };
  32681. /**
  32682. * Updates the WebGL Uniform Buffer on the GPU.
  32683. * If the `dynamic` flag is set to true, no cache comparison is done.
  32684. * Otherwise, the buffer will be updated only if the cache differs.
  32685. */
  32686. UniformBuffer.prototype.update = function () {
  32687. if (!this._buffer) {
  32688. this.create();
  32689. return;
  32690. }
  32691. if (!this._dynamic && !this._needSync) {
  32692. return;
  32693. }
  32694. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32695. this._needSync = false;
  32696. };
  32697. /**
  32698. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32699. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32700. * @param {number[]|Float32Array} data Flattened data
  32701. * @param {number} size Size of the data.
  32702. */
  32703. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32704. var location = this._uniformLocations[uniformName];
  32705. if (location === undefined) {
  32706. if (this._buffer) {
  32707. // Cannot add an uniform if the buffer is already created
  32708. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32709. return;
  32710. }
  32711. this.addUniform(uniformName, size);
  32712. location = this._uniformLocations[uniformName];
  32713. }
  32714. if (!this._buffer) {
  32715. this.create();
  32716. }
  32717. if (!this._dynamic) {
  32718. // Cache for static uniform buffers
  32719. var changed = false;
  32720. for (var i = 0; i < size; i++) {
  32721. if (this._bufferData[location + i] !== data[i]) {
  32722. changed = true;
  32723. this._bufferData[location + i] = data[i];
  32724. }
  32725. }
  32726. this._needSync = this._needSync || changed;
  32727. }
  32728. else {
  32729. // No cache for dynamic
  32730. for (var i = 0; i < size; i++) {
  32731. this._bufferData[location + i] = data[i];
  32732. }
  32733. }
  32734. };
  32735. // Update methods
  32736. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32737. // To match std140, matrix must be realigned
  32738. for (var i = 0; i < 3; i++) {
  32739. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32740. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32741. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32742. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32743. }
  32744. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32745. };
  32746. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32747. this._currentEffect.setMatrix3x3(name, matrix);
  32748. };
  32749. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32750. this._currentEffect.setMatrix2x2(name, matrix);
  32751. };
  32752. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32753. // To match std140, matrix must be realigned
  32754. for (var i = 0; i < 2; i++) {
  32755. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32756. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32757. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32758. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32759. }
  32760. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32761. };
  32762. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32763. this._currentEffect.setFloat(name, x);
  32764. };
  32765. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32766. UniformBuffer._tempBuffer[0] = x;
  32767. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32768. };
  32769. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32770. if (suffix === void 0) { suffix = ""; }
  32771. this._currentEffect.setFloat2(name + suffix, x, y);
  32772. };
  32773. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32774. if (suffix === void 0) { suffix = ""; }
  32775. UniformBuffer._tempBuffer[0] = x;
  32776. UniformBuffer._tempBuffer[1] = y;
  32777. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32778. };
  32779. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32780. if (suffix === void 0) { suffix = ""; }
  32781. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32782. };
  32783. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32784. if (suffix === void 0) { suffix = ""; }
  32785. UniformBuffer._tempBuffer[0] = x;
  32786. UniformBuffer._tempBuffer[1] = y;
  32787. UniformBuffer._tempBuffer[2] = z;
  32788. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32789. };
  32790. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32791. if (suffix === void 0) { suffix = ""; }
  32792. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32793. };
  32794. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32795. if (suffix === void 0) { suffix = ""; }
  32796. UniformBuffer._tempBuffer[0] = x;
  32797. UniformBuffer._tempBuffer[1] = y;
  32798. UniformBuffer._tempBuffer[2] = z;
  32799. UniformBuffer._tempBuffer[3] = w;
  32800. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32801. };
  32802. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32803. this._currentEffect.setMatrix(name, mat);
  32804. };
  32805. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32806. this.updateUniform(name, mat.toArray(), 16);
  32807. };
  32808. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32809. this._currentEffect.setVector3(name, vector);
  32810. };
  32811. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32812. vector.toArray(UniformBuffer._tempBuffer);
  32813. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32814. };
  32815. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32816. this._currentEffect.setVector4(name, vector);
  32817. };
  32818. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32819. vector.toArray(UniformBuffer._tempBuffer);
  32820. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32821. };
  32822. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32823. if (suffix === void 0) { suffix = ""; }
  32824. this._currentEffect.setColor3(name + suffix, color);
  32825. };
  32826. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32827. if (suffix === void 0) { suffix = ""; }
  32828. color.toArray(UniformBuffer._tempBuffer);
  32829. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32830. };
  32831. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32832. if (suffix === void 0) { suffix = ""; }
  32833. this._currentEffect.setColor4(name + suffix, color, alpha);
  32834. };
  32835. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32836. if (suffix === void 0) { suffix = ""; }
  32837. color.toArray(UniformBuffer._tempBuffer);
  32838. UniformBuffer._tempBuffer[3] = alpha;
  32839. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32840. };
  32841. /**
  32842. * Sets a sampler uniform on the effect.
  32843. * @param {string} name Name of the sampler.
  32844. * @param {Texture} texture
  32845. */
  32846. UniformBuffer.prototype.setTexture = function (name, texture) {
  32847. this._currentEffect.setTexture(name, texture);
  32848. };
  32849. /**
  32850. * Directly updates the value of the uniform in the cache AND on the GPU.
  32851. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32852. * @param {number[]|Float32Array} data Flattened data
  32853. */
  32854. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32855. this.updateUniform(uniformName, data, data.length);
  32856. this.update();
  32857. };
  32858. /**
  32859. * Binds this uniform buffer to an effect.
  32860. * @param {Effect} effect
  32861. * @param {string} name Name of the uniform block in the shader.
  32862. */
  32863. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32864. this._currentEffect = effect;
  32865. if (this._noUBO || !this._buffer) {
  32866. return;
  32867. }
  32868. effect.bindUniformBuffer(this._buffer, name);
  32869. };
  32870. /**
  32871. * Disposes the uniform buffer.
  32872. */
  32873. UniformBuffer.prototype.dispose = function () {
  32874. if (this._noUBO) {
  32875. return;
  32876. }
  32877. var index = this._engine._uniformBuffers.indexOf(this);
  32878. if (index !== -1) {
  32879. this._engine._uniformBuffers.splice(index, 1);
  32880. }
  32881. if (!this._buffer) {
  32882. return;
  32883. }
  32884. if (this._engine._releaseBuffer(this._buffer)) {
  32885. this._buffer = null;
  32886. }
  32887. };
  32888. // Pool for avoiding memory leaks
  32889. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32890. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32891. return UniformBuffer;
  32892. }());
  32893. BABYLON.UniformBuffer = UniformBuffer;
  32894. })(BABYLON || (BABYLON = {}));
  32895. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32896. "use strict";
  32897. var BABYLON;
  32898. (function (BABYLON) {
  32899. var VertexData = /** @class */ (function () {
  32900. function VertexData() {
  32901. }
  32902. VertexData.prototype.set = function (data, kind) {
  32903. switch (kind) {
  32904. case BABYLON.VertexBuffer.PositionKind:
  32905. this.positions = data;
  32906. break;
  32907. case BABYLON.VertexBuffer.NormalKind:
  32908. this.normals = data;
  32909. break;
  32910. case BABYLON.VertexBuffer.TangentKind:
  32911. this.tangents = data;
  32912. break;
  32913. case BABYLON.VertexBuffer.UVKind:
  32914. this.uvs = data;
  32915. break;
  32916. case BABYLON.VertexBuffer.UV2Kind:
  32917. this.uvs2 = data;
  32918. break;
  32919. case BABYLON.VertexBuffer.UV3Kind:
  32920. this.uvs3 = data;
  32921. break;
  32922. case BABYLON.VertexBuffer.UV4Kind:
  32923. this.uvs4 = data;
  32924. break;
  32925. case BABYLON.VertexBuffer.UV5Kind:
  32926. this.uvs5 = data;
  32927. break;
  32928. case BABYLON.VertexBuffer.UV6Kind:
  32929. this.uvs6 = data;
  32930. break;
  32931. case BABYLON.VertexBuffer.ColorKind:
  32932. this.colors = data;
  32933. break;
  32934. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32935. this.matricesIndices = data;
  32936. break;
  32937. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32938. this.matricesWeights = data;
  32939. break;
  32940. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32941. this.matricesIndicesExtra = data;
  32942. break;
  32943. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32944. this.matricesWeightsExtra = data;
  32945. break;
  32946. }
  32947. };
  32948. /**
  32949. * Associates the vertexData to the passed Mesh.
  32950. * Sets it as updatable or not (default `false`).
  32951. * Returns the VertexData.
  32952. */
  32953. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32954. this._applyTo(mesh, updatable);
  32955. return this;
  32956. };
  32957. /**
  32958. * Associates the vertexData to the passed Geometry.
  32959. * Sets it as updatable or not (default `false`).
  32960. * Returns the VertexData.
  32961. */
  32962. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32963. this._applyTo(geometry, updatable);
  32964. return this;
  32965. };
  32966. /**
  32967. * Updates the associated mesh.
  32968. * Returns the VertexData.
  32969. */
  32970. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32971. this._update(mesh);
  32972. return this;
  32973. };
  32974. /**
  32975. * Updates the associated geometry.
  32976. * Returns the VertexData.
  32977. */
  32978. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32979. this._update(geometry);
  32980. return this;
  32981. };
  32982. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32983. if (updatable === void 0) { updatable = false; }
  32984. if (this.positions) {
  32985. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32986. }
  32987. if (this.normals) {
  32988. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32989. }
  32990. if (this.tangents) {
  32991. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32992. }
  32993. if (this.uvs) {
  32994. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32995. }
  32996. if (this.uvs2) {
  32997. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32998. }
  32999. if (this.uvs3) {
  33000. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33001. }
  33002. if (this.uvs4) {
  33003. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33004. }
  33005. if (this.uvs5) {
  33006. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33007. }
  33008. if (this.uvs6) {
  33009. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33010. }
  33011. if (this.colors) {
  33012. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33013. }
  33014. if (this.matricesIndices) {
  33015. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33016. }
  33017. if (this.matricesWeights) {
  33018. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33019. }
  33020. if (this.matricesIndicesExtra) {
  33021. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33022. }
  33023. if (this.matricesWeightsExtra) {
  33024. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33025. }
  33026. if (this.indices) {
  33027. meshOrGeometry.setIndices(this.indices, null, updatable);
  33028. }
  33029. return this;
  33030. };
  33031. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33032. if (this.positions) {
  33033. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33034. }
  33035. if (this.normals) {
  33036. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33037. }
  33038. if (this.tangents) {
  33039. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33040. }
  33041. if (this.uvs) {
  33042. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33043. }
  33044. if (this.uvs2) {
  33045. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33046. }
  33047. if (this.uvs3) {
  33048. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33049. }
  33050. if (this.uvs4) {
  33051. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33052. }
  33053. if (this.uvs5) {
  33054. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33055. }
  33056. if (this.uvs6) {
  33057. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33058. }
  33059. if (this.colors) {
  33060. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33061. }
  33062. if (this.matricesIndices) {
  33063. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33064. }
  33065. if (this.matricesWeights) {
  33066. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33067. }
  33068. if (this.matricesIndicesExtra) {
  33069. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33070. }
  33071. if (this.matricesWeightsExtra) {
  33072. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33073. }
  33074. if (this.indices) {
  33075. meshOrGeometry.setIndices(this.indices, null);
  33076. }
  33077. return this;
  33078. };
  33079. /**
  33080. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33081. * Returns the VertexData.
  33082. */
  33083. VertexData.prototype.transform = function (matrix) {
  33084. var transformed = BABYLON.Vector3.Zero();
  33085. var index;
  33086. if (this.positions) {
  33087. var position = BABYLON.Vector3.Zero();
  33088. for (index = 0; index < this.positions.length; index += 3) {
  33089. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33090. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33091. this.positions[index] = transformed.x;
  33092. this.positions[index + 1] = transformed.y;
  33093. this.positions[index + 2] = transformed.z;
  33094. }
  33095. }
  33096. if (this.normals) {
  33097. var normal = BABYLON.Vector3.Zero();
  33098. for (index = 0; index < this.normals.length; index += 3) {
  33099. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33100. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33101. this.normals[index] = transformed.x;
  33102. this.normals[index + 1] = transformed.y;
  33103. this.normals[index + 2] = transformed.z;
  33104. }
  33105. }
  33106. if (this.tangents) {
  33107. var tangent = BABYLON.Vector4.Zero();
  33108. var tangentTransformed = BABYLON.Vector4.Zero();
  33109. for (index = 0; index < this.tangents.length; index += 4) {
  33110. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33111. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33112. this.tangents[index] = tangentTransformed.x;
  33113. this.tangents[index + 1] = tangentTransformed.y;
  33114. this.tangents[index + 2] = tangentTransformed.z;
  33115. this.tangents[index + 3] = tangentTransformed.w;
  33116. }
  33117. }
  33118. return this;
  33119. };
  33120. /**
  33121. * Merges the passed VertexData into the current one.
  33122. * Returns the modified VertexData.
  33123. */
  33124. VertexData.prototype.merge = function (other) {
  33125. this._validate();
  33126. other._validate();
  33127. if (!this.normals !== !other.normals ||
  33128. !this.tangents !== !other.tangents ||
  33129. !this.uvs !== !other.uvs ||
  33130. !this.uvs2 !== !other.uvs2 ||
  33131. !this.uvs3 !== !other.uvs3 ||
  33132. !this.uvs4 !== !other.uvs4 ||
  33133. !this.uvs5 !== !other.uvs5 ||
  33134. !this.uvs6 !== !other.uvs6 ||
  33135. !this.colors !== !other.colors ||
  33136. !this.matricesIndices !== !other.matricesIndices ||
  33137. !this.matricesWeights !== !other.matricesWeights ||
  33138. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33139. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33140. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33141. }
  33142. if (other.indices) {
  33143. if (!this.indices) {
  33144. this.indices = [];
  33145. }
  33146. var offset = this.positions ? this.positions.length / 3 : 0;
  33147. for (var index = 0; index < other.indices.length; index++) {
  33148. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33149. this.indices.push(other.indices[index] + offset);
  33150. }
  33151. }
  33152. this.positions = this._mergeElement(this.positions, other.positions);
  33153. this.normals = this._mergeElement(this.normals, other.normals);
  33154. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33155. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33156. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33157. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33158. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33159. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33160. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33161. this.colors = this._mergeElement(this.colors, other.colors);
  33162. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33163. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33164. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33165. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33166. return this;
  33167. };
  33168. VertexData.prototype._mergeElement = function (source, other) {
  33169. if (!source) {
  33170. return other;
  33171. }
  33172. if (!other) {
  33173. return source;
  33174. }
  33175. var len = other.length + source.length;
  33176. var isSrcTypedArray = source instanceof Float32Array;
  33177. var isOthTypedArray = other instanceof Float32Array;
  33178. // use non-loop method when the source is Float32Array
  33179. if (isSrcTypedArray) {
  33180. var ret32 = new Float32Array(len);
  33181. ret32.set(source);
  33182. ret32.set(other, source.length);
  33183. return ret32;
  33184. // source is number[], when other is also use concat
  33185. }
  33186. else if (!isOthTypedArray) {
  33187. return source.concat(other);
  33188. // source is a number[], but other is a Float32Array, loop required
  33189. }
  33190. else {
  33191. var ret = source.slice(0); // copy source to a separate array
  33192. for (var i = 0, len = other.length; i < len; i++) {
  33193. ret.push(other[i]);
  33194. }
  33195. return ret;
  33196. }
  33197. };
  33198. VertexData.prototype._validate = function () {
  33199. if (!this.positions) {
  33200. throw new Error("Positions are required");
  33201. }
  33202. var getElementCount = function (kind, values) {
  33203. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33204. if ((values.length % stride) !== 0) {
  33205. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33206. }
  33207. return values.length / stride;
  33208. };
  33209. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33210. var validateElementCount = function (kind, values) {
  33211. var elementCount = getElementCount(kind, values);
  33212. if (elementCount !== positionsElementCount) {
  33213. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33214. }
  33215. };
  33216. if (this.normals)
  33217. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33218. if (this.tangents)
  33219. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33220. if (this.uvs)
  33221. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33222. if (this.uvs2)
  33223. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33224. if (this.uvs3)
  33225. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33226. if (this.uvs4)
  33227. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33228. if (this.uvs5)
  33229. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33230. if (this.uvs6)
  33231. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33232. if (this.colors)
  33233. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33234. if (this.matricesIndices)
  33235. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33236. if (this.matricesWeights)
  33237. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33238. if (this.matricesIndicesExtra)
  33239. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33240. if (this.matricesWeightsExtra)
  33241. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33242. };
  33243. /**
  33244. * Serializes the VertexData.
  33245. * Returns a serialized object.
  33246. */
  33247. VertexData.prototype.serialize = function () {
  33248. var serializationObject = this.serialize();
  33249. if (this.positions) {
  33250. serializationObject.positions = this.positions;
  33251. }
  33252. if (this.normals) {
  33253. serializationObject.normals = this.normals;
  33254. }
  33255. if (this.tangents) {
  33256. serializationObject.tangents = this.tangents;
  33257. }
  33258. if (this.uvs) {
  33259. serializationObject.uvs = this.uvs;
  33260. }
  33261. if (this.uvs2) {
  33262. serializationObject.uvs2 = this.uvs2;
  33263. }
  33264. if (this.uvs3) {
  33265. serializationObject.uvs3 = this.uvs3;
  33266. }
  33267. if (this.uvs4) {
  33268. serializationObject.uvs4 = this.uvs4;
  33269. }
  33270. if (this.uvs5) {
  33271. serializationObject.uvs5 = this.uvs5;
  33272. }
  33273. if (this.uvs6) {
  33274. serializationObject.uvs6 = this.uvs6;
  33275. }
  33276. if (this.colors) {
  33277. serializationObject.colors = this.colors;
  33278. }
  33279. if (this.matricesIndices) {
  33280. serializationObject.matricesIndices = this.matricesIndices;
  33281. serializationObject.matricesIndices._isExpanded = true;
  33282. }
  33283. if (this.matricesWeights) {
  33284. serializationObject.matricesWeights = this.matricesWeights;
  33285. }
  33286. if (this.matricesIndicesExtra) {
  33287. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33288. serializationObject.matricesIndicesExtra._isExpanded = true;
  33289. }
  33290. if (this.matricesWeightsExtra) {
  33291. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33292. }
  33293. serializationObject.indices = this.indices;
  33294. return serializationObject;
  33295. };
  33296. // Statics
  33297. /**
  33298. * Returns the object VertexData associated to the passed mesh.
  33299. */
  33300. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33301. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33302. };
  33303. /**
  33304. * Returns the object VertexData associated to the passed geometry.
  33305. */
  33306. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33307. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33308. };
  33309. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33310. var result = new VertexData();
  33311. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33312. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33313. }
  33314. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33315. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33316. }
  33317. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33318. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33319. }
  33320. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33321. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33322. }
  33323. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33324. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33325. }
  33326. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33327. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33328. }
  33329. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33330. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33331. }
  33332. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33333. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33334. }
  33335. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33336. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33337. }
  33338. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33339. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33340. }
  33341. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33342. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33343. }
  33344. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33345. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33346. }
  33347. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33348. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33349. }
  33350. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33351. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33352. }
  33353. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33354. return result;
  33355. };
  33356. /**
  33357. * Creates the vertexData of the Ribbon.
  33358. */
  33359. VertexData.CreateRibbon = function (options) {
  33360. var pathArray = options.pathArray;
  33361. var closeArray = options.closeArray || false;
  33362. var closePath = options.closePath || false;
  33363. var invertUV = options.invertUV || false;
  33364. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33365. var offset = options.offset || defaultOffset;
  33366. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33367. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33368. var customUV = options.uvs;
  33369. var customColors = options.colors;
  33370. var positions = [];
  33371. var indices = [];
  33372. var normals = [];
  33373. var uvs = [];
  33374. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33375. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33376. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33377. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33378. var minlg; // minimal length among all paths from pathArray
  33379. var lg = []; // array of path lengths : nb of vertex per path
  33380. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33381. var p; // path iterator
  33382. var i; // point iterator
  33383. var j; // point iterator
  33384. // if single path in pathArray
  33385. if (pathArray.length < 2) {
  33386. var ar1 = [];
  33387. var ar2 = [];
  33388. for (i = 0; i < pathArray[0].length - offset; i++) {
  33389. ar1.push(pathArray[0][i]);
  33390. ar2.push(pathArray[0][i + offset]);
  33391. }
  33392. pathArray = [ar1, ar2];
  33393. }
  33394. // positions and horizontal distances (u)
  33395. var idc = 0;
  33396. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33397. var path;
  33398. var l;
  33399. minlg = pathArray[0].length;
  33400. var vectlg;
  33401. var dist;
  33402. for (p = 0; p < pathArray.length; p++) {
  33403. uTotalDistance[p] = 0;
  33404. us[p] = [0];
  33405. path = pathArray[p];
  33406. l = path.length;
  33407. minlg = (minlg < l) ? minlg : l;
  33408. j = 0;
  33409. while (j < l) {
  33410. positions.push(path[j].x, path[j].y, path[j].z);
  33411. if (j > 0) {
  33412. vectlg = path[j].subtract(path[j - 1]).length();
  33413. dist = vectlg + uTotalDistance[p];
  33414. us[p].push(dist);
  33415. uTotalDistance[p] = dist;
  33416. }
  33417. j++;
  33418. }
  33419. if (closePath) {
  33420. j--;
  33421. positions.push(path[0].x, path[0].y, path[0].z);
  33422. vectlg = path[j].subtract(path[0]).length();
  33423. dist = vectlg + uTotalDistance[p];
  33424. us[p].push(dist);
  33425. uTotalDistance[p] = dist;
  33426. }
  33427. lg[p] = l + closePathCorr;
  33428. idx[p] = idc;
  33429. idc += (l + closePathCorr);
  33430. }
  33431. // vertical distances (v)
  33432. var path1;
  33433. var path2;
  33434. var vertex1 = null;
  33435. var vertex2 = null;
  33436. for (i = 0; i < minlg + closePathCorr; i++) {
  33437. vTotalDistance[i] = 0;
  33438. vs[i] = [0];
  33439. for (p = 0; p < pathArray.length - 1; p++) {
  33440. path1 = pathArray[p];
  33441. path2 = pathArray[p + 1];
  33442. if (i === minlg) {
  33443. vertex1 = path1[0];
  33444. vertex2 = path2[0];
  33445. }
  33446. else {
  33447. vertex1 = path1[i];
  33448. vertex2 = path2[i];
  33449. }
  33450. vectlg = vertex2.subtract(vertex1).length();
  33451. dist = vectlg + vTotalDistance[i];
  33452. vs[i].push(dist);
  33453. vTotalDistance[i] = dist;
  33454. }
  33455. if (closeArray && vertex2 && vertex1) {
  33456. path1 = pathArray[p];
  33457. path2 = pathArray[0];
  33458. if (i === minlg) {
  33459. vertex2 = path2[0];
  33460. }
  33461. vectlg = vertex2.subtract(vertex1).length();
  33462. dist = vectlg + vTotalDistance[i];
  33463. vTotalDistance[i] = dist;
  33464. }
  33465. }
  33466. // uvs
  33467. var u;
  33468. var v;
  33469. if (customUV) {
  33470. for (p = 0; p < customUV.length; p++) {
  33471. uvs.push(customUV[p].x, customUV[p].y);
  33472. }
  33473. }
  33474. else {
  33475. for (p = 0; p < pathArray.length; p++) {
  33476. for (i = 0; i < minlg + closePathCorr; i++) {
  33477. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33478. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33479. if (invertUV) {
  33480. uvs.push(v, u);
  33481. }
  33482. else {
  33483. uvs.push(u, v);
  33484. }
  33485. }
  33486. }
  33487. }
  33488. // indices
  33489. p = 0; // path index
  33490. var pi = 0; // positions array index
  33491. var l1 = lg[p] - 1; // path1 length
  33492. var l2 = lg[p + 1] - 1; // path2 length
  33493. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33494. var shft = idx[1] - idx[0]; // shift
  33495. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33496. while (pi <= min && p < path1nb) {
  33497. // 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
  33498. indices.push(pi, pi + shft, pi + 1);
  33499. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33500. pi += 1;
  33501. if (pi === min) {
  33502. p++;
  33503. if (p === lg.length - 1) {
  33504. shft = idx[0] - idx[p];
  33505. l1 = lg[p] - 1;
  33506. l2 = lg[0] - 1;
  33507. }
  33508. else {
  33509. shft = idx[p + 1] - idx[p];
  33510. l1 = lg[p] - 1;
  33511. l2 = lg[p + 1] - 1;
  33512. }
  33513. pi = idx[p];
  33514. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33515. }
  33516. }
  33517. // normals
  33518. VertexData.ComputeNormals(positions, indices, normals);
  33519. if (closePath) {
  33520. var indexFirst = 0;
  33521. var indexLast = 0;
  33522. for (p = 0; p < pathArray.length; p++) {
  33523. indexFirst = idx[p] * 3;
  33524. if (p + 1 < pathArray.length) {
  33525. indexLast = (idx[p + 1] - 1) * 3;
  33526. }
  33527. else {
  33528. indexLast = normals.length - 3;
  33529. }
  33530. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33531. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33532. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33533. normals[indexLast] = normals[indexFirst];
  33534. normals[indexLast + 1] = normals[indexFirst + 1];
  33535. normals[indexLast + 2] = normals[indexFirst + 2];
  33536. }
  33537. }
  33538. // sides
  33539. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33540. // Colors
  33541. var colors = null;
  33542. if (customColors) {
  33543. colors = new Float32Array(customColors.length * 4);
  33544. for (var c = 0; c < customColors.length; c++) {
  33545. colors[c * 4] = customColors[c].r;
  33546. colors[c * 4 + 1] = customColors[c].g;
  33547. colors[c * 4 + 2] = customColors[c].b;
  33548. colors[c * 4 + 3] = customColors[c].a;
  33549. }
  33550. }
  33551. // Result
  33552. var vertexData = new VertexData();
  33553. var positions32 = new Float32Array(positions);
  33554. var normals32 = new Float32Array(normals);
  33555. var uvs32 = new Float32Array(uvs);
  33556. vertexData.indices = indices;
  33557. vertexData.positions = positions32;
  33558. vertexData.normals = normals32;
  33559. vertexData.uvs = uvs32;
  33560. if (colors) {
  33561. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33562. }
  33563. if (closePath) {
  33564. vertexData._idx = idx;
  33565. }
  33566. return vertexData;
  33567. };
  33568. /**
  33569. * Creates the VertexData of the Box.
  33570. */
  33571. VertexData.CreateBox = function (options) {
  33572. var normalsSource = [
  33573. new BABYLON.Vector3(0, 0, 1),
  33574. new BABYLON.Vector3(0, 0, -1),
  33575. new BABYLON.Vector3(1, 0, 0),
  33576. new BABYLON.Vector3(-1, 0, 0),
  33577. new BABYLON.Vector3(0, 1, 0),
  33578. new BABYLON.Vector3(0, -1, 0)
  33579. ];
  33580. var indices = [];
  33581. var positions = [];
  33582. var normals = [];
  33583. var uvs = [];
  33584. var width = options.width || options.size || 1;
  33585. var height = options.height || options.size || 1;
  33586. var depth = options.depth || options.size || 1;
  33587. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33588. var faceUV = options.faceUV || new Array(6);
  33589. var faceColors = options.faceColors;
  33590. var colors = [];
  33591. // default face colors and UV if undefined
  33592. for (var f = 0; f < 6; f++) {
  33593. if (faceUV[f] === undefined) {
  33594. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33595. }
  33596. if (faceColors && faceColors[f] === undefined) {
  33597. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33598. }
  33599. }
  33600. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33601. // Create each face in turn.
  33602. for (var index = 0; index < normalsSource.length; index++) {
  33603. var normal = normalsSource[index];
  33604. // Get two vectors perpendicular to the face normal and to each other.
  33605. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33606. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33607. // Six indices (two triangles) per face.
  33608. var verticesLength = positions.length / 3;
  33609. indices.push(verticesLength);
  33610. indices.push(verticesLength + 1);
  33611. indices.push(verticesLength + 2);
  33612. indices.push(verticesLength);
  33613. indices.push(verticesLength + 2);
  33614. indices.push(verticesLength + 3);
  33615. // Four vertices per face.
  33616. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33617. positions.push(vertex.x, vertex.y, vertex.z);
  33618. normals.push(normal.x, normal.y, normal.z);
  33619. uvs.push(faceUV[index].z, faceUV[index].w);
  33620. if (faceColors) {
  33621. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33622. }
  33623. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33624. positions.push(vertex.x, vertex.y, vertex.z);
  33625. normals.push(normal.x, normal.y, normal.z);
  33626. uvs.push(faceUV[index].x, faceUV[index].w);
  33627. if (faceColors) {
  33628. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33629. }
  33630. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33631. positions.push(vertex.x, vertex.y, vertex.z);
  33632. normals.push(normal.x, normal.y, normal.z);
  33633. uvs.push(faceUV[index].x, faceUV[index].y);
  33634. if (faceColors) {
  33635. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33636. }
  33637. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33638. positions.push(vertex.x, vertex.y, vertex.z);
  33639. normals.push(normal.x, normal.y, normal.z);
  33640. uvs.push(faceUV[index].z, faceUV[index].y);
  33641. if (faceColors) {
  33642. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33643. }
  33644. }
  33645. // sides
  33646. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33647. // Result
  33648. var vertexData = new VertexData();
  33649. vertexData.indices = indices;
  33650. vertexData.positions = positions;
  33651. vertexData.normals = normals;
  33652. vertexData.uvs = uvs;
  33653. if (faceColors) {
  33654. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33655. vertexData.colors = totalColors;
  33656. }
  33657. return vertexData;
  33658. };
  33659. /**
  33660. * Creates the VertexData of the Sphere.
  33661. */
  33662. VertexData.CreateSphere = function (options) {
  33663. var segments = options.segments || 32;
  33664. var diameterX = options.diameterX || options.diameter || 1;
  33665. var diameterY = options.diameterY || options.diameter || 1;
  33666. var diameterZ = options.diameterZ || options.diameter || 1;
  33667. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33668. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33669. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33670. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33671. var totalZRotationSteps = 2 + segments;
  33672. var totalYRotationSteps = 2 * totalZRotationSteps;
  33673. var indices = [];
  33674. var positions = [];
  33675. var normals = [];
  33676. var uvs = [];
  33677. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33678. var normalizedZ = zRotationStep / totalZRotationSteps;
  33679. var angleZ = normalizedZ * Math.PI * slice;
  33680. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33681. var normalizedY = yRotationStep / totalYRotationSteps;
  33682. var angleY = normalizedY * Math.PI * 2 * arc;
  33683. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33684. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33685. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33686. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33687. var vertex = complete.multiply(radius);
  33688. var normal = complete.divide(radius).normalize();
  33689. positions.push(vertex.x, vertex.y, vertex.z);
  33690. normals.push(normal.x, normal.y, normal.z);
  33691. uvs.push(normalizedY, normalizedZ);
  33692. }
  33693. if (zRotationStep > 0) {
  33694. var verticesCount = positions.length / 3;
  33695. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33696. indices.push((firstIndex));
  33697. indices.push((firstIndex + 1));
  33698. indices.push(firstIndex + totalYRotationSteps + 1);
  33699. indices.push((firstIndex + totalYRotationSteps + 1));
  33700. indices.push((firstIndex + 1));
  33701. indices.push((firstIndex + totalYRotationSteps + 2));
  33702. }
  33703. }
  33704. }
  33705. // Sides
  33706. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33707. // Result
  33708. var vertexData = new VertexData();
  33709. vertexData.indices = indices;
  33710. vertexData.positions = positions;
  33711. vertexData.normals = normals;
  33712. vertexData.uvs = uvs;
  33713. return vertexData;
  33714. };
  33715. /**
  33716. * Creates the VertexData of the Cylinder or Cone.
  33717. */
  33718. VertexData.CreateCylinder = function (options) {
  33719. var height = options.height || 2;
  33720. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33721. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33722. var tessellation = options.tessellation || 24;
  33723. var subdivisions = options.subdivisions || 1;
  33724. var hasRings = options.hasRings ? true : false;
  33725. var enclose = options.enclose ? true : false;
  33726. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33727. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33728. var faceUV = options.faceUV || new Array(3);
  33729. var faceColors = options.faceColors;
  33730. // default face colors and UV if undefined
  33731. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33732. var ringNb = (hasRings) ? subdivisions : 1;
  33733. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33734. var f;
  33735. for (f = 0; f < surfaceNb; f++) {
  33736. if (faceColors && faceColors[f] === undefined) {
  33737. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33738. }
  33739. }
  33740. for (f = 0; f < surfaceNb; f++) {
  33741. if (faceUV && faceUV[f] === undefined) {
  33742. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33743. }
  33744. }
  33745. var indices = new Array();
  33746. var positions = new Array();
  33747. var normals = new Array();
  33748. var uvs = new Array();
  33749. var colors = new Array();
  33750. var angle_step = Math.PI * 2 * arc / tessellation;
  33751. var angle;
  33752. var h;
  33753. var radius;
  33754. var tan = (diameterBottom - diameterTop) / 2 / height;
  33755. var ringVertex = BABYLON.Vector3.Zero();
  33756. var ringNormal = BABYLON.Vector3.Zero();
  33757. var ringFirstVertex = BABYLON.Vector3.Zero();
  33758. var ringFirstNormal = BABYLON.Vector3.Zero();
  33759. var quadNormal = BABYLON.Vector3.Zero();
  33760. var Y = BABYLON.Axis.Y;
  33761. // positions, normals, uvs
  33762. var i;
  33763. var j;
  33764. var r;
  33765. var ringIdx = 1;
  33766. var s = 1; // surface index
  33767. var cs = 0;
  33768. var v = 0;
  33769. for (i = 0; i <= subdivisions; i++) {
  33770. h = i / subdivisions;
  33771. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33772. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33773. for (r = 0; r < ringIdx; r++) {
  33774. if (hasRings) {
  33775. s += r;
  33776. }
  33777. if (enclose) {
  33778. s += 2 * r;
  33779. }
  33780. for (j = 0; j <= tessellation; j++) {
  33781. angle = j * angle_step;
  33782. // position
  33783. ringVertex.x = Math.cos(-angle) * radius;
  33784. ringVertex.y = -height / 2 + h * height;
  33785. ringVertex.z = Math.sin(-angle) * radius;
  33786. // normal
  33787. if (diameterTop === 0 && i === subdivisions) {
  33788. // if no top cap, reuse former normals
  33789. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33790. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33791. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33792. }
  33793. else {
  33794. ringNormal.x = ringVertex.x;
  33795. ringNormal.z = ringVertex.z;
  33796. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33797. ringNormal.normalize();
  33798. }
  33799. // keep first ring vertex values for enclose
  33800. if (j === 0) {
  33801. ringFirstVertex.copyFrom(ringVertex);
  33802. ringFirstNormal.copyFrom(ringNormal);
  33803. }
  33804. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33805. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33806. if (hasRings) {
  33807. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33808. }
  33809. else {
  33810. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33811. }
  33812. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33813. if (faceColors) {
  33814. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33815. }
  33816. }
  33817. // if enclose, add four vertices and their dedicated normals
  33818. if (arc !== 1 && enclose) {
  33819. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33820. positions.push(0, ringVertex.y, 0);
  33821. positions.push(0, ringVertex.y, 0);
  33822. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33823. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33824. quadNormal.normalize();
  33825. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33826. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33827. quadNormal.normalize();
  33828. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33829. if (hasRings) {
  33830. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33831. }
  33832. else {
  33833. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33834. }
  33835. uvs.push(faceUV[s + 1].x, v);
  33836. uvs.push(faceUV[s + 1].z, v);
  33837. if (hasRings) {
  33838. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33839. }
  33840. else {
  33841. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33842. }
  33843. uvs.push(faceUV[s + 2].x, v);
  33844. uvs.push(faceUV[s + 2].z, v);
  33845. if (faceColors) {
  33846. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33847. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33848. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33849. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33850. }
  33851. }
  33852. if (cs !== s) {
  33853. cs = s;
  33854. }
  33855. }
  33856. }
  33857. // indices
  33858. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33859. var s;
  33860. i = 0;
  33861. for (s = 0; s < subdivisions; s++) {
  33862. var i0 = 0;
  33863. var i1 = 0;
  33864. var i2 = 0;
  33865. var i3 = 0;
  33866. for (j = 0; j < tessellation; j++) {
  33867. i0 = i * (e + 1) + j;
  33868. i1 = (i + 1) * (e + 1) + j;
  33869. i2 = i * (e + 1) + (j + 1);
  33870. i3 = (i + 1) * (e + 1) + (j + 1);
  33871. indices.push(i0, i1, i2);
  33872. indices.push(i3, i2, i1);
  33873. }
  33874. if (arc !== 1 && enclose) {
  33875. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33876. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33877. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33878. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33879. }
  33880. i = (hasRings) ? (i + 2) : (i + 1);
  33881. }
  33882. // Caps
  33883. var createCylinderCap = function (isTop) {
  33884. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33885. if (radius === 0) {
  33886. return;
  33887. }
  33888. // Cap positions, normals & uvs
  33889. var angle;
  33890. var circleVector;
  33891. var i;
  33892. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33893. var c = null;
  33894. if (faceColors) {
  33895. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33896. }
  33897. // cap center
  33898. var vbase = positions.length / 3;
  33899. var offset = isTop ? height / 2 : -height / 2;
  33900. var center = new BABYLON.Vector3(0, offset, 0);
  33901. positions.push(center.x, center.y, center.z);
  33902. normals.push(0, isTop ? 1 : -1, 0);
  33903. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33904. if (c) {
  33905. colors.push(c.r, c.g, c.b, c.a);
  33906. }
  33907. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33908. for (i = 0; i <= tessellation; i++) {
  33909. angle = Math.PI * 2 * i * arc / tessellation;
  33910. var cos = Math.cos(-angle);
  33911. var sin = Math.sin(-angle);
  33912. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33913. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33914. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33915. normals.push(0, isTop ? 1 : -1, 0);
  33916. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33917. if (c) {
  33918. colors.push(c.r, c.g, c.b, c.a);
  33919. }
  33920. }
  33921. // Cap indices
  33922. for (i = 0; i < tessellation; i++) {
  33923. if (!isTop) {
  33924. indices.push(vbase);
  33925. indices.push(vbase + (i + 1));
  33926. indices.push(vbase + (i + 2));
  33927. }
  33928. else {
  33929. indices.push(vbase);
  33930. indices.push(vbase + (i + 2));
  33931. indices.push(vbase + (i + 1));
  33932. }
  33933. }
  33934. };
  33935. // add caps to geometry
  33936. createCylinderCap(false);
  33937. createCylinderCap(true);
  33938. // Sides
  33939. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33940. var vertexData = new VertexData();
  33941. vertexData.indices = indices;
  33942. vertexData.positions = positions;
  33943. vertexData.normals = normals;
  33944. vertexData.uvs = uvs;
  33945. if (faceColors) {
  33946. vertexData.colors = colors;
  33947. }
  33948. return vertexData;
  33949. };
  33950. /**
  33951. * Creates the VertexData of the Torus.
  33952. */
  33953. VertexData.CreateTorus = function (options) {
  33954. var indices = [];
  33955. var positions = [];
  33956. var normals = [];
  33957. var uvs = [];
  33958. var diameter = options.diameter || 1;
  33959. var thickness = options.thickness || 0.5;
  33960. var tessellation = options.tessellation || 16;
  33961. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33962. var stride = tessellation + 1;
  33963. for (var i = 0; i <= tessellation; i++) {
  33964. var u = i / tessellation;
  33965. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33966. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33967. for (var j = 0; j <= tessellation; j++) {
  33968. var v = 1 - j / tessellation;
  33969. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33970. var dx = Math.cos(innerAngle);
  33971. var dy = Math.sin(innerAngle);
  33972. // Create a vertex.
  33973. var normal = new BABYLON.Vector3(dx, dy, 0);
  33974. var position = normal.scale(thickness / 2);
  33975. var textureCoordinate = new BABYLON.Vector2(u, v);
  33976. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33977. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33978. positions.push(position.x, position.y, position.z);
  33979. normals.push(normal.x, normal.y, normal.z);
  33980. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33981. // And create indices for two triangles.
  33982. var nextI = (i + 1) % stride;
  33983. var nextJ = (j + 1) % stride;
  33984. indices.push(i * stride + j);
  33985. indices.push(i * stride + nextJ);
  33986. indices.push(nextI * stride + j);
  33987. indices.push(i * stride + nextJ);
  33988. indices.push(nextI * stride + nextJ);
  33989. indices.push(nextI * stride + j);
  33990. }
  33991. }
  33992. // Sides
  33993. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33994. // Result
  33995. var vertexData = new VertexData();
  33996. vertexData.indices = indices;
  33997. vertexData.positions = positions;
  33998. vertexData.normals = normals;
  33999. vertexData.uvs = uvs;
  34000. return vertexData;
  34001. };
  34002. /**
  34003. * Creates the VertexData of the LineSystem.
  34004. */
  34005. VertexData.CreateLineSystem = function (options) {
  34006. var indices = [];
  34007. var positions = [];
  34008. var lines = options.lines;
  34009. var colors = options.colors;
  34010. var vertexColors = [];
  34011. var idx = 0;
  34012. for (var l = 0; l < lines.length; l++) {
  34013. var points = lines[l];
  34014. for (var index = 0; index < points.length; index++) {
  34015. positions.push(points[index].x, points[index].y, points[index].z);
  34016. if (colors) {
  34017. var color = colors[l];
  34018. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  34019. }
  34020. if (index > 0) {
  34021. indices.push(idx - 1);
  34022. indices.push(idx);
  34023. }
  34024. idx++;
  34025. }
  34026. }
  34027. var vertexData = new VertexData();
  34028. vertexData.indices = indices;
  34029. vertexData.positions = positions;
  34030. if (colors) {
  34031. vertexData.colors = vertexColors;
  34032. }
  34033. return vertexData;
  34034. };
  34035. /**
  34036. * Create the VertexData of the DashedLines.
  34037. */
  34038. VertexData.CreateDashedLines = function (options) {
  34039. var dashSize = options.dashSize || 3;
  34040. var gapSize = options.gapSize || 1;
  34041. var dashNb = options.dashNb || 200;
  34042. var points = options.points;
  34043. var positions = new Array();
  34044. var indices = new Array();
  34045. var curvect = BABYLON.Vector3.Zero();
  34046. var lg = 0;
  34047. var nb = 0;
  34048. var shft = 0;
  34049. var dashshft = 0;
  34050. var curshft = 0;
  34051. var idx = 0;
  34052. var i = 0;
  34053. for (i = 0; i < points.length - 1; i++) {
  34054. points[i + 1].subtractToRef(points[i], curvect);
  34055. lg += curvect.length();
  34056. }
  34057. shft = lg / dashNb;
  34058. dashshft = dashSize * shft / (dashSize + gapSize);
  34059. for (i = 0; i < points.length - 1; i++) {
  34060. points[i + 1].subtractToRef(points[i], curvect);
  34061. nb = Math.floor(curvect.length() / shft);
  34062. curvect.normalize();
  34063. for (var j = 0; j < nb; j++) {
  34064. curshft = shft * j;
  34065. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34066. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34067. indices.push(idx, idx + 1);
  34068. idx += 2;
  34069. }
  34070. }
  34071. // Result
  34072. var vertexData = new VertexData();
  34073. vertexData.positions = positions;
  34074. vertexData.indices = indices;
  34075. return vertexData;
  34076. };
  34077. /**
  34078. * Creates the VertexData of the Ground.
  34079. */
  34080. VertexData.CreateGround = function (options) {
  34081. var indices = [];
  34082. var positions = [];
  34083. var normals = [];
  34084. var uvs = [];
  34085. var row, col;
  34086. var width = options.width || 1;
  34087. var height = options.height || 1;
  34088. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34089. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34090. for (row = 0; row <= subdivisionsY; row++) {
  34091. for (col = 0; col <= subdivisionsX; col++) {
  34092. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34093. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34094. positions.push(position.x, position.y, position.z);
  34095. normals.push(normal.x, normal.y, normal.z);
  34096. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34097. }
  34098. }
  34099. for (row = 0; row < subdivisionsY; row++) {
  34100. for (col = 0; col < subdivisionsX; col++) {
  34101. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34102. indices.push(col + 1 + row * (subdivisionsX + 1));
  34103. indices.push(col + row * (subdivisionsX + 1));
  34104. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34105. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34106. indices.push(col + row * (subdivisionsX + 1));
  34107. }
  34108. }
  34109. // Result
  34110. var vertexData = new VertexData();
  34111. vertexData.indices = indices;
  34112. vertexData.positions = positions;
  34113. vertexData.normals = normals;
  34114. vertexData.uvs = uvs;
  34115. return vertexData;
  34116. };
  34117. /**
  34118. * Creates the VertexData of the TiledGround.
  34119. */
  34120. VertexData.CreateTiledGround = function (options) {
  34121. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34122. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34123. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34124. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34125. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34126. var precision = options.precision || { w: 1, h: 1 };
  34127. var indices = new Array();
  34128. var positions = new Array();
  34129. var normals = new Array();
  34130. var uvs = new Array();
  34131. var row, col, tileRow, tileCol;
  34132. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34133. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34134. precision.w = (precision.w < 1) ? 1 : precision.w;
  34135. precision.h = (precision.h < 1) ? 1 : precision.h;
  34136. var tileSize = {
  34137. 'w': (xmax - xmin) / subdivisions.w,
  34138. 'h': (zmax - zmin) / subdivisions.h
  34139. };
  34140. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34141. // Indices
  34142. var base = positions.length / 3;
  34143. var rowLength = precision.w + 1;
  34144. for (row = 0; row < precision.h; row++) {
  34145. for (col = 0; col < precision.w; col++) {
  34146. var square = [
  34147. base + col + row * rowLength,
  34148. base + (col + 1) + row * rowLength,
  34149. base + (col + 1) + (row + 1) * rowLength,
  34150. base + col + (row + 1) * rowLength
  34151. ];
  34152. indices.push(square[1]);
  34153. indices.push(square[2]);
  34154. indices.push(square[3]);
  34155. indices.push(square[0]);
  34156. indices.push(square[1]);
  34157. indices.push(square[3]);
  34158. }
  34159. }
  34160. // Position, normals and uvs
  34161. var position = BABYLON.Vector3.Zero();
  34162. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34163. for (row = 0; row <= precision.h; row++) {
  34164. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34165. for (col = 0; col <= precision.w; col++) {
  34166. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34167. position.y = 0;
  34168. positions.push(position.x, position.y, position.z);
  34169. normals.push(normal.x, normal.y, normal.z);
  34170. uvs.push(col / precision.w, row / precision.h);
  34171. }
  34172. }
  34173. }
  34174. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34175. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34176. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34177. }
  34178. }
  34179. // Result
  34180. var vertexData = new VertexData();
  34181. vertexData.indices = indices;
  34182. vertexData.positions = positions;
  34183. vertexData.normals = normals;
  34184. vertexData.uvs = uvs;
  34185. return vertexData;
  34186. };
  34187. /**
  34188. * Creates the VertexData of the Ground designed from a heightmap.
  34189. */
  34190. VertexData.CreateGroundFromHeightMap = function (options) {
  34191. var indices = [];
  34192. var positions = [];
  34193. var normals = [];
  34194. var uvs = [];
  34195. var row, col;
  34196. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34197. // Vertices
  34198. for (row = 0; row <= options.subdivisions; row++) {
  34199. for (col = 0; col <= options.subdivisions; col++) {
  34200. 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));
  34201. // Compute height
  34202. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34203. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34204. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34205. var r = options.buffer[pos] / 255.0;
  34206. var g = options.buffer[pos + 1] / 255.0;
  34207. var b = options.buffer[pos + 2] / 255.0;
  34208. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34209. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34210. // Add vertex
  34211. positions.push(position.x, position.y, position.z);
  34212. normals.push(0, 0, 0);
  34213. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34214. }
  34215. }
  34216. // Indices
  34217. for (row = 0; row < options.subdivisions; row++) {
  34218. for (col = 0; col < options.subdivisions; col++) {
  34219. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34220. indices.push(col + 1 + row * (options.subdivisions + 1));
  34221. indices.push(col + row * (options.subdivisions + 1));
  34222. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34223. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34224. indices.push(col + row * (options.subdivisions + 1));
  34225. }
  34226. }
  34227. // Normals
  34228. VertexData.ComputeNormals(positions, indices, normals);
  34229. // Result
  34230. var vertexData = new VertexData();
  34231. vertexData.indices = indices;
  34232. vertexData.positions = positions;
  34233. vertexData.normals = normals;
  34234. vertexData.uvs = uvs;
  34235. return vertexData;
  34236. };
  34237. /**
  34238. * Creates the VertexData of the Plane.
  34239. */
  34240. VertexData.CreatePlane = function (options) {
  34241. var indices = [];
  34242. var positions = [];
  34243. var normals = [];
  34244. var uvs = [];
  34245. var width = options.width || options.size || 1;
  34246. var height = options.height || options.size || 1;
  34247. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34248. // Vertices
  34249. var halfWidth = width / 2.0;
  34250. var halfHeight = height / 2.0;
  34251. positions.push(-halfWidth, -halfHeight, 0);
  34252. normals.push(0, 0, -1.0);
  34253. uvs.push(0.0, 0.0);
  34254. positions.push(halfWidth, -halfHeight, 0);
  34255. normals.push(0, 0, -1.0);
  34256. uvs.push(1.0, 0.0);
  34257. positions.push(halfWidth, halfHeight, 0);
  34258. normals.push(0, 0, -1.0);
  34259. uvs.push(1.0, 1.0);
  34260. positions.push(-halfWidth, halfHeight, 0);
  34261. normals.push(0, 0, -1.0);
  34262. uvs.push(0.0, 1.0);
  34263. // Indices
  34264. indices.push(0);
  34265. indices.push(1);
  34266. indices.push(2);
  34267. indices.push(0);
  34268. indices.push(2);
  34269. indices.push(3);
  34270. // Sides
  34271. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34272. // Result
  34273. var vertexData = new VertexData();
  34274. vertexData.indices = indices;
  34275. vertexData.positions = positions;
  34276. vertexData.normals = normals;
  34277. vertexData.uvs = uvs;
  34278. return vertexData;
  34279. };
  34280. /**
  34281. * Creates the VertexData of the Disc or regular Polygon.
  34282. */
  34283. VertexData.CreateDisc = function (options) {
  34284. var positions = new Array();
  34285. var indices = new Array();
  34286. var normals = new Array();
  34287. var uvs = new Array();
  34288. var radius = options.radius || 0.5;
  34289. var tessellation = options.tessellation || 64;
  34290. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34291. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34292. // positions and uvs
  34293. positions.push(0, 0, 0); // disc center first
  34294. uvs.push(0.5, 0.5);
  34295. var theta = Math.PI * 2 * arc;
  34296. var step = theta / tessellation;
  34297. for (var a = 0; a < theta; a += step) {
  34298. var x = Math.cos(a);
  34299. var y = Math.sin(a);
  34300. var u = (x + 1) / 2;
  34301. var v = (1 - y) / 2;
  34302. positions.push(radius * x, radius * y, 0);
  34303. uvs.push(u, v);
  34304. }
  34305. if (arc === 1) {
  34306. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34307. uvs.push(uvs[2], uvs[3]);
  34308. }
  34309. //indices
  34310. var vertexNb = positions.length / 3;
  34311. for (var i = 1; i < vertexNb - 1; i++) {
  34312. indices.push(i + 1, 0, i);
  34313. }
  34314. // result
  34315. VertexData.ComputeNormals(positions, indices, normals);
  34316. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34317. var vertexData = new VertexData();
  34318. vertexData.indices = indices;
  34319. vertexData.positions = positions;
  34320. vertexData.normals = normals;
  34321. vertexData.uvs = uvs;
  34322. return vertexData;
  34323. };
  34324. /**
  34325. * Re-creates the VertexData of the Polygon for sideOrientation.
  34326. */
  34327. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34328. var faceUV = fUV || new Array(3);
  34329. var faceColors = fColors;
  34330. var colors = [];
  34331. // default face colors and UV if undefined
  34332. for (var f = 0; f < 3; f++) {
  34333. if (faceUV[f] === undefined) {
  34334. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34335. }
  34336. if (faceColors && faceColors[f] === undefined) {
  34337. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34338. }
  34339. }
  34340. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34341. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34342. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34343. var indices = polygon.getIndices();
  34344. // set face colours and textures
  34345. var idx = 0;
  34346. var face = 0;
  34347. for (var index = 0; index < normals.length; index += 3) {
  34348. //Edge Face no. 1
  34349. if (Math.abs(normals[index + 1]) < 0.001) {
  34350. face = 1;
  34351. }
  34352. //Top Face no. 0
  34353. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34354. face = 0;
  34355. }
  34356. //Bottom Face no. 2
  34357. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34358. face = 2;
  34359. }
  34360. idx = index / 3;
  34361. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34362. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34363. if (faceColors) {
  34364. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34365. }
  34366. }
  34367. // sides
  34368. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34369. // Result
  34370. var vertexData = new VertexData();
  34371. vertexData.indices = indices;
  34372. vertexData.positions = positions;
  34373. vertexData.normals = normals;
  34374. vertexData.uvs = uvs;
  34375. if (faceColors) {
  34376. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34377. vertexData.colors = totalColors;
  34378. }
  34379. return vertexData;
  34380. };
  34381. /**
  34382. * Creates the VertexData of the IcoSphere.
  34383. */
  34384. VertexData.CreateIcoSphere = function (options) {
  34385. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34386. var radius = options.radius || 1;
  34387. var flat = (options.flat === undefined) ? true : options.flat;
  34388. var subdivisions = options.subdivisions || 4;
  34389. var radiusX = options.radiusX || radius;
  34390. var radiusY = options.radiusY || radius;
  34391. var radiusZ = options.radiusZ || radius;
  34392. var t = (1 + Math.sqrt(5)) / 2;
  34393. // 12 vertex x,y,z
  34394. var ico_vertices = [
  34395. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34396. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34397. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34398. ];
  34399. // index of 3 vertex makes a face of icopshere
  34400. var ico_indices = [
  34401. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34402. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34403. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34404. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34405. ];
  34406. // vertex for uv have aliased position, not for UV
  34407. var vertices_unalias_id = [
  34408. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34409. // vertex alias
  34410. 0,
  34411. 2,
  34412. 3,
  34413. 3,
  34414. 3,
  34415. 4,
  34416. 7,
  34417. 8,
  34418. 9,
  34419. 9,
  34420. 10,
  34421. 11 // 23: B + 12
  34422. ];
  34423. // uv as integer step (not pixels !)
  34424. var ico_vertexuv = [
  34425. 5, 1, 3, 1, 6, 4, 0, 0,
  34426. 5, 3, 4, 2, 2, 2, 4, 0,
  34427. 2, 0, 1, 1, 6, 0, 6, 2,
  34428. // vertex alias (for same vertex on different faces)
  34429. 0, 4,
  34430. 3, 3,
  34431. 4, 4,
  34432. 3, 1,
  34433. 4, 2,
  34434. 4, 4,
  34435. 0, 2,
  34436. 1, 1,
  34437. 2, 2,
  34438. 3, 3,
  34439. 1, 3,
  34440. 2, 4 // 23: B + 12
  34441. ];
  34442. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34443. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34444. // First island of uv mapping
  34445. // v = 4h 3+ 2
  34446. // v = 3h 9+ 4
  34447. // v = 2h 9+ 5 B
  34448. // v = 1h 9 1 0
  34449. // v = 0h 3 8 7 A
  34450. // u = 0 1 2 3 4 5 6 *a
  34451. // Second island of uv mapping
  34452. // v = 4h 0+ B+ 4+
  34453. // v = 3h A+ 2+
  34454. // v = 2h 7+ 6 3+
  34455. // v = 1h 8+ 3+
  34456. // v = 0h
  34457. // u = 0 1 2 3 4 5 6 *a
  34458. // Face layout on texture UV mapping
  34459. // ============
  34460. // \ 4 /\ 16 / ======
  34461. // \ / \ / /\ 11 /
  34462. // \/ 7 \/ / \ /
  34463. // ======= / 10 \/
  34464. // /\ 17 /\ =======
  34465. // / \ / \ \ 15 /\
  34466. // / 8 \/ 12 \ \ / \
  34467. // ============ \/ 6 \
  34468. // \ 18 /\ ============
  34469. // \ / \ \ 5 /\ 0 /
  34470. // \/ 13 \ \ / \ /
  34471. // ======= \/ 1 \/
  34472. // =============
  34473. // /\ 19 /\ 2 /\
  34474. // / \ / \ / \
  34475. // / 14 \/ 9 \/ 3 \
  34476. // ===================
  34477. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34478. var ustep = 138 / 1024;
  34479. var vstep = 239 / 1024;
  34480. var uoffset = 60 / 1024;
  34481. var voffset = 26 / 1024;
  34482. // Second island should have margin, not to touch the first island
  34483. // avoid any borderline artefact in pixel rounding
  34484. var island_u_offset = -40 / 1024;
  34485. var island_v_offset = +20 / 1024;
  34486. // face is either island 0 or 1 :
  34487. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34488. var island = [
  34489. 0, 0, 0, 0, 1,
  34490. 0, 0, 1, 1, 0,
  34491. 0, 0, 1, 1, 0,
  34492. 0, 1, 1, 1, 0 // 15 - 19
  34493. ];
  34494. var indices = new Array();
  34495. var positions = new Array();
  34496. var normals = new Array();
  34497. var uvs = new Array();
  34498. var current_indice = 0;
  34499. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34500. var face_vertex_pos = new Array(3);
  34501. var face_vertex_uv = new Array(3);
  34502. var v012;
  34503. for (v012 = 0; v012 < 3; v012++) {
  34504. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34505. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34506. }
  34507. // create all with normals
  34508. for (var face = 0; face < 20; face++) {
  34509. // 3 vertex per face
  34510. for (v012 = 0; v012 < 3; v012++) {
  34511. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34512. var v_id = ico_indices[3 * face + v012];
  34513. // vertex have 3D position (x,y,z)
  34514. 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]);
  34515. // Normalize to get normal, then scale to radius
  34516. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34517. // uv Coordinates from vertex ID
  34518. 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);
  34519. }
  34520. // Subdivide the face (interpolate pos, norm, uv)
  34521. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34522. // - norm is linear interpolation of vertex corner normal
  34523. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34524. // - uv is linear interpolation
  34525. //
  34526. // Topology is as below for sub-divide by 2
  34527. // vertex shown as v0,v1,v2
  34528. // interp index is i1 to progress in range [v0,v1[
  34529. // interp index is i2 to progress in range [v0,v2[
  34530. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34531. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34532. //
  34533. //
  34534. // i2 v2
  34535. // ^ ^
  34536. // / / \
  34537. // / / \
  34538. // / / \
  34539. // / / (0,1) \
  34540. // / #---------\
  34541. // / / \ (0,0)'/ \
  34542. // / / \ / \
  34543. // / / \ / \
  34544. // / / (0,0) \ / (1,0) \
  34545. // / #---------#---------\
  34546. // v0 v1
  34547. //
  34548. // --------------------> i1
  34549. //
  34550. // interp of (i1,i2):
  34551. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34552. // along i1 : lerp(x0,x1, i1/(S-i2))
  34553. //
  34554. // centroid of triangle is needed to get help normal computation
  34555. // (c1,c2) are used for centroid location
  34556. var interp_vertex = function (i1, i2, c1, c2) {
  34557. // vertex is interpolated from
  34558. // - face_vertex_pos[0..2]
  34559. // - face_vertex_uv[0..2]
  34560. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34561. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34562. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34563. pos_interp.normalize();
  34564. var vertex_normal;
  34565. if (flat) {
  34566. // in flat mode, recalculate normal as face centroid normal
  34567. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34568. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34569. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34570. }
  34571. else {
  34572. // in smooth mode, recalculate normal from each single vertex position
  34573. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34574. }
  34575. // Vertex normal need correction due to X,Y,Z radius scaling
  34576. vertex_normal.x /= radiusX;
  34577. vertex_normal.y /= radiusY;
  34578. vertex_normal.z /= radiusZ;
  34579. vertex_normal.normalize();
  34580. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34581. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34582. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34583. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34584. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34585. uvs.push(uv_interp.x, uv_interp.y);
  34586. // push each vertex has member of a face
  34587. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34588. indices.push(current_indice);
  34589. current_indice++;
  34590. };
  34591. for (var i2 = 0; i2 < subdivisions; i2++) {
  34592. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34593. // face : (i1,i2) for /\ :
  34594. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34595. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34596. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34597. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34598. if (i1 + i2 + 1 < subdivisions) {
  34599. // face : (i1,i2)' for \/ :
  34600. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34601. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34602. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34603. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34604. }
  34605. }
  34606. }
  34607. }
  34608. // Sides
  34609. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34610. // Result
  34611. var vertexData = new VertexData();
  34612. vertexData.indices = indices;
  34613. vertexData.positions = positions;
  34614. vertexData.normals = normals;
  34615. vertexData.uvs = uvs;
  34616. return vertexData;
  34617. };
  34618. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34619. /**
  34620. * Creates the VertexData of the Polyhedron.
  34621. */
  34622. VertexData.CreatePolyhedron = function (options) {
  34623. // provided polyhedron types :
  34624. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34625. // 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)
  34626. var polyhedra = [];
  34627. 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]] };
  34628. 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]] };
  34629. polyhedra[2] = {
  34630. 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]],
  34631. 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]]
  34632. };
  34633. polyhedra[3] = {
  34634. 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]],
  34635. 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]]
  34636. };
  34637. polyhedra[4] = {
  34638. 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]],
  34639. 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]]
  34640. };
  34641. 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]] };
  34642. 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]] };
  34643. 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]] };
  34644. 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]] };
  34645. 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]] };
  34646. 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]] };
  34647. 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]] };
  34648. 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]] };
  34649. 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]] };
  34650. polyhedra[14] = {
  34651. 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]],
  34652. 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]]
  34653. };
  34654. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34655. var size = options.size;
  34656. var sizeX = options.sizeX || size || 1;
  34657. var sizeY = options.sizeY || size || 1;
  34658. var sizeZ = options.sizeZ || size || 1;
  34659. var data = options.custom || polyhedra[type];
  34660. var nbfaces = data.face.length;
  34661. var faceUV = options.faceUV || new Array(nbfaces);
  34662. var faceColors = options.faceColors;
  34663. var flat = (options.flat === undefined) ? true : options.flat;
  34664. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34665. var positions = new Array();
  34666. var indices = new Array();
  34667. var normals = new Array();
  34668. var uvs = new Array();
  34669. var colors = new Array();
  34670. var index = 0;
  34671. var faceIdx = 0; // face cursor in the array "indexes"
  34672. var indexes = new Array();
  34673. var i = 0;
  34674. var f = 0;
  34675. var u, v, ang, x, y, tmp;
  34676. // default face colors and UV if undefined
  34677. if (flat) {
  34678. for (f = 0; f < nbfaces; f++) {
  34679. if (faceColors && faceColors[f] === undefined) {
  34680. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34681. }
  34682. if (faceUV && faceUV[f] === undefined) {
  34683. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34684. }
  34685. }
  34686. }
  34687. if (!flat) {
  34688. for (i = 0; i < data.vertex.length; i++) {
  34689. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34690. uvs.push(0, 0);
  34691. }
  34692. for (f = 0; f < nbfaces; f++) {
  34693. for (i = 0; i < data.face[f].length - 2; i++) {
  34694. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34695. }
  34696. }
  34697. }
  34698. else {
  34699. for (f = 0; f < nbfaces; f++) {
  34700. var fl = data.face[f].length; // number of vertices of the current face
  34701. ang = 2 * Math.PI / fl;
  34702. x = 0.5 * Math.tan(ang / 2);
  34703. y = 0.5;
  34704. // positions, uvs, colors
  34705. for (i = 0; i < fl; i++) {
  34706. // positions
  34707. 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);
  34708. indexes.push(index);
  34709. index++;
  34710. // uvs
  34711. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34712. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34713. uvs.push(u, v);
  34714. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34715. y = x * Math.sin(ang) + y * Math.cos(ang);
  34716. x = tmp;
  34717. // colors
  34718. if (faceColors) {
  34719. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34720. }
  34721. }
  34722. // indices from indexes
  34723. for (i = 0; i < fl - 2; i++) {
  34724. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34725. }
  34726. faceIdx += fl;
  34727. }
  34728. }
  34729. VertexData.ComputeNormals(positions, indices, normals);
  34730. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34731. var vertexData = new VertexData();
  34732. vertexData.positions = positions;
  34733. vertexData.indices = indices;
  34734. vertexData.normals = normals;
  34735. vertexData.uvs = uvs;
  34736. if (faceColors && flat) {
  34737. vertexData.colors = colors;
  34738. }
  34739. return vertexData;
  34740. };
  34741. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34742. /**
  34743. * Creates the VertexData of the Torus Knot.
  34744. */
  34745. VertexData.CreateTorusKnot = function (options) {
  34746. var indices = new Array();
  34747. var positions = new Array();
  34748. var normals = new Array();
  34749. var uvs = new Array();
  34750. var radius = options.radius || 2;
  34751. var tube = options.tube || 0.5;
  34752. var radialSegments = options.radialSegments || 32;
  34753. var tubularSegments = options.tubularSegments || 32;
  34754. var p = options.p || 2;
  34755. var q = options.q || 3;
  34756. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34757. // Helper
  34758. var getPos = function (angle) {
  34759. var cu = Math.cos(angle);
  34760. var su = Math.sin(angle);
  34761. var quOverP = q / p * angle;
  34762. var cs = Math.cos(quOverP);
  34763. var tx = radius * (2 + cs) * 0.5 * cu;
  34764. var ty = radius * (2 + cs) * su * 0.5;
  34765. var tz = radius * Math.sin(quOverP) * 0.5;
  34766. return new BABYLON.Vector3(tx, ty, tz);
  34767. };
  34768. // Vertices
  34769. var i;
  34770. var j;
  34771. for (i = 0; i <= radialSegments; i++) {
  34772. var modI = i % radialSegments;
  34773. var u = modI / radialSegments * 2 * p * Math.PI;
  34774. var p1 = getPos(u);
  34775. var p2 = getPos(u + 0.01);
  34776. var tang = p2.subtract(p1);
  34777. var n = p2.add(p1);
  34778. var bitan = BABYLON.Vector3.Cross(tang, n);
  34779. n = BABYLON.Vector3.Cross(bitan, tang);
  34780. bitan.normalize();
  34781. n.normalize();
  34782. for (j = 0; j < tubularSegments; j++) {
  34783. var modJ = j % tubularSegments;
  34784. var v = modJ / tubularSegments * 2 * Math.PI;
  34785. var cx = -tube * Math.cos(v);
  34786. var cy = tube * Math.sin(v);
  34787. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34788. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34789. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34790. uvs.push(i / radialSegments);
  34791. uvs.push(j / tubularSegments);
  34792. }
  34793. }
  34794. for (i = 0; i < radialSegments; i++) {
  34795. for (j = 0; j < tubularSegments; j++) {
  34796. var jNext = (j + 1) % tubularSegments;
  34797. var a = i * tubularSegments + j;
  34798. var b = (i + 1) * tubularSegments + j;
  34799. var c = (i + 1) * tubularSegments + jNext;
  34800. var d = i * tubularSegments + jNext;
  34801. indices.push(d);
  34802. indices.push(b);
  34803. indices.push(a);
  34804. indices.push(d);
  34805. indices.push(c);
  34806. indices.push(b);
  34807. }
  34808. }
  34809. // Normals
  34810. VertexData.ComputeNormals(positions, indices, normals);
  34811. // Sides
  34812. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34813. // Result
  34814. var vertexData = new VertexData();
  34815. vertexData.indices = indices;
  34816. vertexData.positions = positions;
  34817. vertexData.normals = normals;
  34818. vertexData.uvs = uvs;
  34819. return vertexData;
  34820. };
  34821. // Tools
  34822. /**
  34823. * @param {any} - positions (number[] or Float32Array)
  34824. * @param {any} - indices (number[] or Uint16Array)
  34825. * @param {any} - normals (number[] or Float32Array)
  34826. * options (optional) :
  34827. * facetPositions : optional array of facet positions (vector3)
  34828. * facetNormals : optional array of facet normals (vector3)
  34829. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34830. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34831. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34832. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34833. * bInfo : optional bounding info, required for facetPartitioning computation
  34834. * useRightHandedSystem: optional boolean to for right handed system computation
  34835. * depthSort : optional boolean to enable the facet depth sort computation
  34836. * distanceTo : optional Vector3 to compute the facet depth from this location
  34837. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34838. */
  34839. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34840. // temporary scalar variables
  34841. var index = 0; // facet index
  34842. var p1p2x = 0.0; // p1p2 vector x coordinate
  34843. var p1p2y = 0.0; // p1p2 vector y coordinate
  34844. var p1p2z = 0.0; // p1p2 vector z coordinate
  34845. var p3p2x = 0.0; // p3p2 vector x coordinate
  34846. var p3p2y = 0.0; // p3p2 vector y coordinate
  34847. var p3p2z = 0.0; // p3p2 vector z coordinate
  34848. var faceNormalx = 0.0; // facet normal x coordinate
  34849. var faceNormaly = 0.0; // facet normal y coordinate
  34850. var faceNormalz = 0.0; // facet normal z coordinate
  34851. var length = 0.0; // facet normal length before normalization
  34852. var v1x = 0; // vector1 x index in the positions array
  34853. var v1y = 0; // vector1 y index in the positions array
  34854. var v1z = 0; // vector1 z index in the positions array
  34855. var v2x = 0; // vector2 x index in the positions array
  34856. var v2y = 0; // vector2 y index in the positions array
  34857. var v2z = 0; // vector2 z index in the positions array
  34858. var v3x = 0; // vector3 x index in the positions array
  34859. var v3y = 0; // vector3 y index in the positions array
  34860. var v3z = 0; // vector3 z index in the positions array
  34861. var computeFacetNormals = false;
  34862. var computeFacetPositions = false;
  34863. var computeFacetPartitioning = false;
  34864. var computeDepthSort = false;
  34865. var faceNormalSign = 1;
  34866. var ratio = 0;
  34867. var distanceTo = null;
  34868. if (options) {
  34869. computeFacetNormals = (options.facetNormals) ? true : false;
  34870. computeFacetPositions = (options.facetPositions) ? true : false;
  34871. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34872. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34873. ratio = options.ratio || 0;
  34874. computeDepthSort = (options.depthSort) ? true : false;
  34875. distanceTo = (options.distanceTo);
  34876. if (computeDepthSort) {
  34877. if (distanceTo === undefined) {
  34878. distanceTo = BABYLON.Vector3.Zero();
  34879. }
  34880. var depthSortedFacets = options.depthSortedFacets;
  34881. }
  34882. }
  34883. // facetPartitioning reinit if needed
  34884. var xSubRatio = 0;
  34885. var ySubRatio = 0;
  34886. var zSubRatio = 0;
  34887. var subSq = 0;
  34888. if (computeFacetPartitioning && options && options.bbSize) {
  34889. var ox = 0; // X partitioning index for facet position
  34890. var oy = 0; // Y partinioning index for facet position
  34891. var oz = 0; // Z partinioning index for facet position
  34892. var b1x = 0; // X partitioning index for facet v1 vertex
  34893. var b1y = 0; // Y partitioning index for facet v1 vertex
  34894. var b1z = 0; // z partitioning index for facet v1 vertex
  34895. var b2x = 0; // X partitioning index for facet v2 vertex
  34896. var b2y = 0; // Y partitioning index for facet v2 vertex
  34897. var b2z = 0; // Z partitioning index for facet v2 vertex
  34898. var b3x = 0; // X partitioning index for facet v3 vertex
  34899. var b3y = 0; // Y partitioning index for facet v3 vertex
  34900. var b3z = 0; // Z partitioning index for facet v3 vertex
  34901. var block_idx_o = 0; // facet barycenter block index
  34902. var block_idx_v1 = 0; // v1 vertex block index
  34903. var block_idx_v2 = 0; // v2 vertex block index
  34904. var block_idx_v3 = 0; // v3 vertex block index
  34905. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34906. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34907. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34908. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34909. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34910. subSq = options.subDiv.max * options.subDiv.max;
  34911. options.facetPartitioning.length = 0;
  34912. }
  34913. // reset the normals
  34914. for (index = 0; index < positions.length; index++) {
  34915. normals[index] = 0.0;
  34916. }
  34917. // Loop : 1 indice triplet = 1 facet
  34918. var nbFaces = (indices.length / 3) | 0;
  34919. for (index = 0; index < nbFaces; index++) {
  34920. // get the indexes of the coordinates of each vertex of the facet
  34921. v1x = indices[index * 3] * 3;
  34922. v1y = v1x + 1;
  34923. v1z = v1x + 2;
  34924. v2x = indices[index * 3 + 1] * 3;
  34925. v2y = v2x + 1;
  34926. v2z = v2x + 2;
  34927. v3x = indices[index * 3 + 2] * 3;
  34928. v3y = v3x + 1;
  34929. v3z = v3x + 2;
  34930. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34931. p1p2y = positions[v1y] - positions[v2y];
  34932. p1p2z = positions[v1z] - positions[v2z];
  34933. p3p2x = positions[v3x] - positions[v2x];
  34934. p3p2y = positions[v3y] - positions[v2y];
  34935. p3p2z = positions[v3z] - positions[v2z];
  34936. // compute the face normal with the cross product
  34937. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34938. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34939. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34940. // normalize this normal and store it in the array facetData
  34941. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34942. length = (length === 0) ? 1.0 : length;
  34943. faceNormalx /= length;
  34944. faceNormaly /= length;
  34945. faceNormalz /= length;
  34946. if (computeFacetNormals && options) {
  34947. options.facetNormals[index].x = faceNormalx;
  34948. options.facetNormals[index].y = faceNormaly;
  34949. options.facetNormals[index].z = faceNormalz;
  34950. }
  34951. if (computeFacetPositions && options) {
  34952. // compute and the facet barycenter coordinates in the array facetPositions
  34953. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34954. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34955. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34956. }
  34957. if (computeFacetPartitioning && options) {
  34958. // store the facet indexes in arrays in the main facetPartitioning array :
  34959. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34960. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34961. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34962. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34963. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34964. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34965. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34966. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34967. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34968. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34969. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34970. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34971. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34972. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34973. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34974. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34975. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34976. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34977. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34978. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34979. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34980. // push each facet index in each block containing the vertex
  34981. options.facetPartitioning[block_idx_v1].push(index);
  34982. if (block_idx_v2 != block_idx_v1) {
  34983. options.facetPartitioning[block_idx_v2].push(index);
  34984. }
  34985. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34986. options.facetPartitioning[block_idx_v3].push(index);
  34987. }
  34988. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34989. options.facetPartitioning[block_idx_o].push(index);
  34990. }
  34991. }
  34992. if (computeDepthSort && options && options.facetPositions) {
  34993. var dsf = depthSortedFacets[index];
  34994. dsf.ind = index * 3;
  34995. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34996. }
  34997. // compute the normals anyway
  34998. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34999. normals[v1y] += faceNormaly;
  35000. normals[v1z] += faceNormalz;
  35001. normals[v2x] += faceNormalx;
  35002. normals[v2y] += faceNormaly;
  35003. normals[v2z] += faceNormalz;
  35004. normals[v3x] += faceNormalx;
  35005. normals[v3y] += faceNormaly;
  35006. normals[v3z] += faceNormalz;
  35007. }
  35008. // last normalization of each normal
  35009. for (index = 0; index < normals.length / 3; index++) {
  35010. faceNormalx = normals[index * 3];
  35011. faceNormaly = normals[index * 3 + 1];
  35012. faceNormalz = normals[index * 3 + 2];
  35013. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35014. length = (length === 0) ? 1.0 : length;
  35015. faceNormalx /= length;
  35016. faceNormaly /= length;
  35017. faceNormalz /= length;
  35018. normals[index * 3] = faceNormalx;
  35019. normals[index * 3 + 1] = faceNormaly;
  35020. normals[index * 3 + 2] = faceNormalz;
  35021. }
  35022. };
  35023. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  35024. var li = indices.length;
  35025. var ln = normals.length;
  35026. var i;
  35027. var n;
  35028. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35029. switch (sideOrientation) {
  35030. case BABYLON.Mesh.FRONTSIDE:
  35031. // nothing changed
  35032. break;
  35033. case BABYLON.Mesh.BACKSIDE:
  35034. var tmp;
  35035. // indices
  35036. for (i = 0; i < li; i += 3) {
  35037. tmp = indices[i];
  35038. indices[i] = indices[i + 2];
  35039. indices[i + 2] = tmp;
  35040. }
  35041. // normals
  35042. for (n = 0; n < ln; n++) {
  35043. normals[n] = -normals[n];
  35044. }
  35045. break;
  35046. case BABYLON.Mesh.DOUBLESIDE:
  35047. // positions
  35048. var lp = positions.length;
  35049. var l = lp / 3;
  35050. for (var p = 0; p < lp; p++) {
  35051. positions[lp + p] = positions[p];
  35052. }
  35053. // indices
  35054. for (i = 0; i < li; i += 3) {
  35055. indices[i + li] = indices[i + 2] + l;
  35056. indices[i + 1 + li] = indices[i + 1] + l;
  35057. indices[i + 2 + li] = indices[i] + l;
  35058. }
  35059. // normals
  35060. for (n = 0; n < ln; n++) {
  35061. normals[ln + n] = -normals[n];
  35062. }
  35063. // uvs
  35064. var lu = uvs.length;
  35065. var u = 0;
  35066. for (u = 0; u < lu; u++) {
  35067. uvs[u + lu] = uvs[u];
  35068. }
  35069. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35070. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35071. u = 0;
  35072. for (i = 0; i < lu / 2; i++) {
  35073. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35074. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35075. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35076. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35077. u += 2;
  35078. }
  35079. break;
  35080. }
  35081. };
  35082. /**
  35083. * Creates a new VertexData from the imported parameters.
  35084. */
  35085. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35086. var vertexData = new VertexData();
  35087. // positions
  35088. var positions = parsedVertexData.positions;
  35089. if (positions) {
  35090. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35091. }
  35092. // normals
  35093. var normals = parsedVertexData.normals;
  35094. if (normals) {
  35095. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35096. }
  35097. // tangents
  35098. var tangents = parsedVertexData.tangents;
  35099. if (tangents) {
  35100. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35101. }
  35102. // uvs
  35103. var uvs = parsedVertexData.uvs;
  35104. if (uvs) {
  35105. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35106. }
  35107. // uv2s
  35108. var uv2s = parsedVertexData.uv2s;
  35109. if (uv2s) {
  35110. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35111. }
  35112. // uv3s
  35113. var uv3s = parsedVertexData.uv3s;
  35114. if (uv3s) {
  35115. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35116. }
  35117. // uv4s
  35118. var uv4s = parsedVertexData.uv4s;
  35119. if (uv4s) {
  35120. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35121. }
  35122. // uv5s
  35123. var uv5s = parsedVertexData.uv5s;
  35124. if (uv5s) {
  35125. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35126. }
  35127. // uv6s
  35128. var uv6s = parsedVertexData.uv6s;
  35129. if (uv6s) {
  35130. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35131. }
  35132. // colors
  35133. var colors = parsedVertexData.colors;
  35134. if (colors) {
  35135. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35136. }
  35137. // matricesIndices
  35138. var matricesIndices = parsedVertexData.matricesIndices;
  35139. if (matricesIndices) {
  35140. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35141. }
  35142. // matricesWeights
  35143. var matricesWeights = parsedVertexData.matricesWeights;
  35144. if (matricesWeights) {
  35145. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35146. }
  35147. // indices
  35148. var indices = parsedVertexData.indices;
  35149. if (indices) {
  35150. vertexData.indices = indices;
  35151. }
  35152. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35153. };
  35154. return VertexData;
  35155. }());
  35156. BABYLON.VertexData = VertexData;
  35157. })(BABYLON || (BABYLON = {}));
  35158. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35159. "use strict";
  35160. var BABYLON;
  35161. (function (BABYLON) {
  35162. /**
  35163. * Class used to store geometry data (vertex buffers + index buffer)
  35164. */
  35165. var Geometry = /** @class */ (function () {
  35166. /**
  35167. * Creates a new geometry
  35168. * @param id defines the unique ID
  35169. * @param scene defines the hosting scene
  35170. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35171. * @param updatable defines if geometry must be updatable (false by default)
  35172. * @param mesh defines the mesh that will be associated with the geometry
  35173. */
  35174. function Geometry(id, scene, vertexData, updatable, mesh) {
  35175. if (updatable === void 0) { updatable = false; }
  35176. if (mesh === void 0) { mesh = null; }
  35177. /**
  35178. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35179. */
  35180. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35181. this._totalVertices = 0;
  35182. this._isDisposed = false;
  35183. this._indexBufferIsUpdatable = false;
  35184. this.id = id;
  35185. this._engine = scene.getEngine();
  35186. this._meshes = [];
  35187. this._scene = scene;
  35188. //Init vertex buffer cache
  35189. this._vertexBuffers = {};
  35190. this._indices = [];
  35191. this._updatable = updatable;
  35192. // vertexData
  35193. if (vertexData) {
  35194. this.setAllVerticesData(vertexData, updatable);
  35195. }
  35196. else {
  35197. this._totalVertices = 0;
  35198. this._indices = [];
  35199. }
  35200. if (this._engine.getCaps().vertexArrayObject) {
  35201. this._vertexArrayObjects = {};
  35202. }
  35203. // applyToMesh
  35204. if (mesh) {
  35205. if (mesh.getClassName() === "LinesMesh") {
  35206. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35207. this.updateExtend();
  35208. }
  35209. this.applyToMesh(mesh);
  35210. mesh.computeWorldMatrix(true);
  35211. }
  35212. }
  35213. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35214. /**
  35215. * 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
  35216. */
  35217. get: function () {
  35218. return this._boundingBias;
  35219. },
  35220. /**
  35221. * 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
  35222. */
  35223. set: function (value) {
  35224. if (this._boundingBias && this._boundingBias.equals(value)) {
  35225. return;
  35226. }
  35227. this._boundingBias = value.clone();
  35228. this.updateBoundingInfo(true, null);
  35229. },
  35230. enumerable: true,
  35231. configurable: true
  35232. });
  35233. /**
  35234. * Static function used to attach a new empty geometry to a mesh
  35235. * @param mesh defines the mesh to attach the geometry to
  35236. * @returns the new {BABYLON.Geometry}
  35237. */
  35238. Geometry.CreateGeometryForMesh = function (mesh) {
  35239. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35240. geometry.applyToMesh(mesh);
  35241. return geometry;
  35242. };
  35243. Object.defineProperty(Geometry.prototype, "extend", {
  35244. /**
  35245. * Gets the current extend of the geometry
  35246. */
  35247. get: function () {
  35248. return this._extend;
  35249. },
  35250. enumerable: true,
  35251. configurable: true
  35252. });
  35253. /**
  35254. * Gets the hosting scene
  35255. * @returns the hosting {BABYLON.Scene}
  35256. */
  35257. Geometry.prototype.getScene = function () {
  35258. return this._scene;
  35259. };
  35260. /**
  35261. * Gets the hosting engine
  35262. * @returns the hosting {BABYLON.Engine}
  35263. */
  35264. Geometry.prototype.getEngine = function () {
  35265. return this._engine;
  35266. };
  35267. /**
  35268. * Defines if the geometry is ready to use
  35269. * @returns true if the geometry is ready to be used
  35270. */
  35271. Geometry.prototype.isReady = function () {
  35272. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35273. };
  35274. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35275. /**
  35276. * Gets a value indicating that the geometry should not be serialized
  35277. */
  35278. get: function () {
  35279. for (var index = 0; index < this._meshes.length; index++) {
  35280. if (!this._meshes[index].doNotSerialize) {
  35281. return false;
  35282. }
  35283. }
  35284. return true;
  35285. },
  35286. enumerable: true,
  35287. configurable: true
  35288. });
  35289. /** @ignore */
  35290. Geometry.prototype._rebuild = function () {
  35291. if (this._vertexArrayObjects) {
  35292. this._vertexArrayObjects = {};
  35293. }
  35294. // Index buffer
  35295. if (this._meshes.length !== 0 && this._indices) {
  35296. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35297. }
  35298. // Vertex buffers
  35299. for (var key in this._vertexBuffers) {
  35300. var vertexBuffer = this._vertexBuffers[key];
  35301. vertexBuffer._rebuild();
  35302. }
  35303. };
  35304. /**
  35305. * Affects all gemetry data in one call
  35306. * @param vertexData defines the geometry data
  35307. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35308. */
  35309. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35310. vertexData.applyToGeometry(this, updatable);
  35311. this.notifyUpdate();
  35312. };
  35313. /**
  35314. * Set specific vertex data
  35315. * @param kind defines the data kind (Position, normal, etc...)
  35316. * @param data defines the vertex data to use
  35317. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35318. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35319. */
  35320. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35321. if (updatable === void 0) { updatable = false; }
  35322. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35323. this.setVerticesBuffer(buffer);
  35324. };
  35325. /**
  35326. * Removes a specific vertex data
  35327. * @param kind defines the data kind (Position, normal, etc...)
  35328. */
  35329. Geometry.prototype.removeVerticesData = function (kind) {
  35330. if (this._vertexBuffers[kind]) {
  35331. this._vertexBuffers[kind].dispose();
  35332. delete this._vertexBuffers[kind];
  35333. }
  35334. };
  35335. /**
  35336. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35337. * @param buffer defines the vertex buffer to use
  35338. */
  35339. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35340. var kind = buffer.getKind();
  35341. if (this._vertexBuffers[kind]) {
  35342. this._vertexBuffers[kind].dispose();
  35343. }
  35344. this._vertexBuffers[kind] = buffer;
  35345. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35346. var data = buffer.getData();
  35347. var stride = buffer.getStrideSize();
  35348. this._totalVertices = data.length / stride;
  35349. this.updateExtend(data, stride);
  35350. this._resetPointsArrayCache();
  35351. var meshes = this._meshes;
  35352. var numOfMeshes = meshes.length;
  35353. for (var index = 0; index < numOfMeshes; index++) {
  35354. var mesh = meshes[index];
  35355. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35356. mesh._createGlobalSubMesh(false);
  35357. mesh.computeWorldMatrix(true);
  35358. }
  35359. }
  35360. this.notifyUpdate(kind);
  35361. if (this._vertexArrayObjects) {
  35362. this._disposeVertexArrayObjects();
  35363. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35364. }
  35365. };
  35366. /**
  35367. * Update a specific vertex buffer
  35368. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35369. * It will do nothing if the buffer is not updatable
  35370. * @param kind defines the data kind (Position, normal, etc...)
  35371. * @param data defines the data to use
  35372. * @param offset defines the offset in the target buffer where to store the data
  35373. */
  35374. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35375. var vertexBuffer = this.getVertexBuffer(kind);
  35376. if (!vertexBuffer) {
  35377. return;
  35378. }
  35379. vertexBuffer.updateDirectly(data, offset);
  35380. this.notifyUpdate(kind);
  35381. };
  35382. /**
  35383. * Update a specific vertex buffer
  35384. * This function will create a new buffer if the current one is not updatable
  35385. * @param kind defines the data kind (Position, normal, etc...)
  35386. * @param data defines the data to use
  35387. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35388. */
  35389. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35390. if (updateExtends === void 0) { updateExtends = false; }
  35391. var vertexBuffer = this.getVertexBuffer(kind);
  35392. if (!vertexBuffer) {
  35393. return;
  35394. }
  35395. vertexBuffer.update(data);
  35396. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35397. var stride = vertexBuffer.getStrideSize();
  35398. this._totalVertices = data.length / stride;
  35399. this.updateBoundingInfo(updateExtends, data);
  35400. }
  35401. this.notifyUpdate(kind);
  35402. };
  35403. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35404. if (updateExtends) {
  35405. this.updateExtend(data);
  35406. }
  35407. var meshes = this._meshes;
  35408. var numOfMeshes = meshes.length;
  35409. this._resetPointsArrayCache();
  35410. for (var index = 0; index < numOfMeshes; index++) {
  35411. var mesh = meshes[index];
  35412. if (updateExtends) {
  35413. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35414. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35415. var subMesh = mesh.subMeshes[subIndex];
  35416. subMesh.refreshBoundingInfo();
  35417. }
  35418. }
  35419. }
  35420. };
  35421. /** @ignore */
  35422. Geometry.prototype._bind = function (effect, indexToBind) {
  35423. if (!effect) {
  35424. return;
  35425. }
  35426. if (indexToBind === undefined) {
  35427. indexToBind = this._indexBuffer;
  35428. }
  35429. var vbs = this.getVertexBuffers();
  35430. if (!vbs) {
  35431. return;
  35432. }
  35433. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35434. this._engine.bindBuffers(vbs, indexToBind, effect);
  35435. return;
  35436. }
  35437. // Using VAO
  35438. if (!this._vertexArrayObjects[effect.key]) {
  35439. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35440. }
  35441. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35442. };
  35443. /**
  35444. * Gets total number of vertices
  35445. * @returns the total number of vertices
  35446. */
  35447. Geometry.prototype.getTotalVertices = function () {
  35448. if (!this.isReady()) {
  35449. return 0;
  35450. }
  35451. return this._totalVertices;
  35452. };
  35453. /**
  35454. * Gets a specific vertex data attached to this geometry
  35455. * @param kind defines the data kind (Position, normal, etc...)
  35456. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35457. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35458. * @returns a float array containing vertex data
  35459. */
  35460. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35461. var vertexBuffer = this.getVertexBuffer(kind);
  35462. if (!vertexBuffer) {
  35463. return null;
  35464. }
  35465. var orig = vertexBuffer.getData();
  35466. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35467. return orig;
  35468. }
  35469. else {
  35470. var len = orig.length;
  35471. var copy = [];
  35472. for (var i = 0; i < len; i++) {
  35473. copy.push(orig[i]);
  35474. }
  35475. return copy;
  35476. }
  35477. };
  35478. /**
  35479. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35480. * @param kind defines the data kind (Position, normal, etc...)
  35481. * @returns true if the vertex buffer with the specified kind is updatable
  35482. */
  35483. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35484. var vb = this._vertexBuffers[kind];
  35485. if (!vb) {
  35486. return false;
  35487. }
  35488. return vb.isUpdatable();
  35489. };
  35490. /**
  35491. * Gets a specific vertex buffer
  35492. * @param kind defines the data kind (Position, normal, etc...)
  35493. * @returns a {BABYLON.VertexBuffer}
  35494. */
  35495. Geometry.prototype.getVertexBuffer = function (kind) {
  35496. if (!this.isReady()) {
  35497. return null;
  35498. }
  35499. return this._vertexBuffers[kind];
  35500. };
  35501. /**
  35502. * Returns all vertex buffers
  35503. * @return an object holding all vertex buffers indexed by kind
  35504. */
  35505. Geometry.prototype.getVertexBuffers = function () {
  35506. if (!this.isReady()) {
  35507. return null;
  35508. }
  35509. return this._vertexBuffers;
  35510. };
  35511. /**
  35512. * Gets a boolean indicating if specific vertex buffer is present
  35513. * @param kind defines the data kind (Position, normal, etc...)
  35514. * @returns true if data is present
  35515. */
  35516. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35517. if (!this._vertexBuffers) {
  35518. if (this._delayInfo) {
  35519. return this._delayInfo.indexOf(kind) !== -1;
  35520. }
  35521. return false;
  35522. }
  35523. return this._vertexBuffers[kind] !== undefined;
  35524. };
  35525. /**
  35526. * Gets a list of all attached data kinds (Position, normal, etc...)
  35527. * @returns a list of string containing all kinds
  35528. */
  35529. Geometry.prototype.getVerticesDataKinds = function () {
  35530. var result = [];
  35531. var kind;
  35532. if (!this._vertexBuffers && this._delayInfo) {
  35533. for (kind in this._delayInfo) {
  35534. result.push(kind);
  35535. }
  35536. }
  35537. else {
  35538. for (kind in this._vertexBuffers) {
  35539. result.push(kind);
  35540. }
  35541. }
  35542. return result;
  35543. };
  35544. /**
  35545. * Update index buffer
  35546. * @param indices defines the indices to store in the index buffer
  35547. * @param offset defines the offset in the target buffer where to store the data
  35548. */
  35549. Geometry.prototype.updateIndices = function (indices, offset) {
  35550. if (!this._indexBuffer) {
  35551. return;
  35552. }
  35553. if (!this._indexBufferIsUpdatable) {
  35554. this.setIndices(indices, null, true);
  35555. }
  35556. else {
  35557. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35558. }
  35559. };
  35560. /**
  35561. * Creates a new index buffer
  35562. * @param indices defines the indices to store in the index buffer
  35563. * @param totalVertices defines the total number of vertices (could be null)
  35564. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35565. */
  35566. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35567. if (totalVertices === void 0) { totalVertices = null; }
  35568. if (updatable === void 0) { updatable = false; }
  35569. if (this._indexBuffer) {
  35570. this._engine._releaseBuffer(this._indexBuffer);
  35571. }
  35572. this._disposeVertexArrayObjects();
  35573. this._indices = indices;
  35574. this._indexBufferIsUpdatable = updatable;
  35575. if (this._meshes.length !== 0 && this._indices) {
  35576. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35577. }
  35578. if (totalVertices != undefined) {
  35579. this._totalVertices = totalVertices;
  35580. }
  35581. var meshes = this._meshes;
  35582. var numOfMeshes = meshes.length;
  35583. for (var index = 0; index < numOfMeshes; index++) {
  35584. meshes[index]._createGlobalSubMesh(true);
  35585. }
  35586. this.notifyUpdate();
  35587. };
  35588. /**
  35589. * Return the total number of indices
  35590. * @returns the total number of indices
  35591. */
  35592. Geometry.prototype.getTotalIndices = function () {
  35593. if (!this.isReady()) {
  35594. return 0;
  35595. }
  35596. return this._indices.length;
  35597. };
  35598. /**
  35599. * Gets the index buffer array
  35600. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35601. * @returns the index buffer array
  35602. */
  35603. Geometry.prototype.getIndices = function (copyWhenShared) {
  35604. if (!this.isReady()) {
  35605. return null;
  35606. }
  35607. var orig = this._indices;
  35608. if (!copyWhenShared || this._meshes.length === 1) {
  35609. return orig;
  35610. }
  35611. else {
  35612. var len = orig.length;
  35613. var copy = [];
  35614. for (var i = 0; i < len; i++) {
  35615. copy.push(orig[i]);
  35616. }
  35617. return copy;
  35618. }
  35619. };
  35620. /**
  35621. * Gets the index buffer
  35622. * @return the index buffer
  35623. */
  35624. Geometry.prototype.getIndexBuffer = function () {
  35625. if (!this.isReady()) {
  35626. return null;
  35627. }
  35628. return this._indexBuffer;
  35629. };
  35630. /** @ignore */
  35631. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35632. if (effect === void 0) { effect = null; }
  35633. if (!effect || !this._vertexArrayObjects) {
  35634. return;
  35635. }
  35636. if (this._vertexArrayObjects[effect.key]) {
  35637. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35638. delete this._vertexArrayObjects[effect.key];
  35639. }
  35640. };
  35641. /**
  35642. * Release the associated resources for a specific mesh
  35643. * @param mesh defines the source mesh
  35644. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35645. */
  35646. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35647. var meshes = this._meshes;
  35648. var index = meshes.indexOf(mesh);
  35649. if (index === -1) {
  35650. return;
  35651. }
  35652. meshes.splice(index, 1);
  35653. mesh._geometry = null;
  35654. if (meshes.length === 0 && shouldDispose) {
  35655. this.dispose();
  35656. }
  35657. };
  35658. /**
  35659. * Apply current geometry to a given mesh
  35660. * @param mesh defines the mesh to apply geometry to
  35661. */
  35662. Geometry.prototype.applyToMesh = function (mesh) {
  35663. if (mesh._geometry === this) {
  35664. return;
  35665. }
  35666. var previousGeometry = mesh._geometry;
  35667. if (previousGeometry) {
  35668. previousGeometry.releaseForMesh(mesh);
  35669. }
  35670. var meshes = this._meshes;
  35671. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35672. mesh._geometry = this;
  35673. this._scene.pushGeometry(this);
  35674. meshes.push(mesh);
  35675. if (this.isReady()) {
  35676. this._applyToMesh(mesh);
  35677. }
  35678. else {
  35679. mesh._boundingInfo = this._boundingInfo;
  35680. }
  35681. };
  35682. Geometry.prototype.updateExtend = function (data, stride) {
  35683. if (data === void 0) { data = null; }
  35684. if (!data) {
  35685. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35686. }
  35687. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35688. };
  35689. Geometry.prototype._applyToMesh = function (mesh) {
  35690. var numOfMeshes = this._meshes.length;
  35691. // vertexBuffers
  35692. for (var kind in this._vertexBuffers) {
  35693. if (numOfMeshes === 1) {
  35694. this._vertexBuffers[kind].create();
  35695. }
  35696. var buffer = this._vertexBuffers[kind].getBuffer();
  35697. if (buffer)
  35698. buffer.references = numOfMeshes;
  35699. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35700. if (!this._extend) {
  35701. this.updateExtend(this._vertexBuffers[kind].getData());
  35702. }
  35703. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35704. mesh._createGlobalSubMesh(false);
  35705. //bounding info was just created again, world matrix should be applied again.
  35706. mesh._updateBoundingInfo();
  35707. }
  35708. }
  35709. // indexBuffer
  35710. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35711. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35712. }
  35713. if (this._indexBuffer) {
  35714. this._indexBuffer.references = numOfMeshes;
  35715. }
  35716. };
  35717. Geometry.prototype.notifyUpdate = function (kind) {
  35718. if (this.onGeometryUpdated) {
  35719. this.onGeometryUpdated(this, kind);
  35720. }
  35721. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35722. var mesh = _a[_i];
  35723. mesh._markSubMeshesAsAttributesDirty();
  35724. }
  35725. };
  35726. /**
  35727. * Load the geometry if it was flagged as delay loaded
  35728. * @param scene defines the hosting scene
  35729. * @param onLoaded defines a callback called when the geometry is loaded
  35730. */
  35731. Geometry.prototype.load = function (scene, onLoaded) {
  35732. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35733. return;
  35734. }
  35735. if (this.isReady()) {
  35736. if (onLoaded) {
  35737. onLoaded();
  35738. }
  35739. return;
  35740. }
  35741. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35742. this._queueLoad(scene, onLoaded);
  35743. };
  35744. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35745. var _this = this;
  35746. if (!this.delayLoadingFile) {
  35747. return;
  35748. }
  35749. scene._addPendingData(this);
  35750. scene._loadFile(this.delayLoadingFile, function (data) {
  35751. if (!_this._delayLoadingFunction) {
  35752. return;
  35753. }
  35754. _this._delayLoadingFunction(JSON.parse(data), _this);
  35755. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35756. _this._delayInfo = [];
  35757. scene._removePendingData(_this);
  35758. var meshes = _this._meshes;
  35759. var numOfMeshes = meshes.length;
  35760. for (var index = 0; index < numOfMeshes; index++) {
  35761. _this._applyToMesh(meshes[index]);
  35762. }
  35763. if (onLoaded) {
  35764. onLoaded();
  35765. }
  35766. }, undefined, true);
  35767. };
  35768. /**
  35769. * Invert the geometry to move from a right handed system to a left handed one.
  35770. */
  35771. Geometry.prototype.toLeftHanded = function () {
  35772. // Flip faces
  35773. var tIndices = this.getIndices(false);
  35774. if (tIndices != null && tIndices.length > 0) {
  35775. for (var i = 0; i < tIndices.length; i += 3) {
  35776. var tTemp = tIndices[i + 0];
  35777. tIndices[i + 0] = tIndices[i + 2];
  35778. tIndices[i + 2] = tTemp;
  35779. }
  35780. this.setIndices(tIndices);
  35781. }
  35782. // Negate position.z
  35783. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35784. if (tPositions != null && tPositions.length > 0) {
  35785. for (var i = 0; i < tPositions.length; i += 3) {
  35786. tPositions[i + 2] = -tPositions[i + 2];
  35787. }
  35788. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35789. }
  35790. // Negate normal.z
  35791. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35792. if (tNormals != null && tNormals.length > 0) {
  35793. for (var i = 0; i < tNormals.length; i += 3) {
  35794. tNormals[i + 2] = -tNormals[i + 2];
  35795. }
  35796. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35797. }
  35798. };
  35799. // Cache
  35800. /** @ignore */
  35801. Geometry.prototype._resetPointsArrayCache = function () {
  35802. this._positions = null;
  35803. };
  35804. /** @ignore */
  35805. Geometry.prototype._generatePointsArray = function () {
  35806. if (this._positions)
  35807. return true;
  35808. this._positions = [];
  35809. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35810. if (!data) {
  35811. return false;
  35812. }
  35813. for (var index = 0; index < data.length; index += 3) {
  35814. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35815. }
  35816. return true;
  35817. };
  35818. /**
  35819. * Gets a value indicating if the geometry is disposed
  35820. * @returns true if the geometry was disposed
  35821. */
  35822. Geometry.prototype.isDisposed = function () {
  35823. return this._isDisposed;
  35824. };
  35825. Geometry.prototype._disposeVertexArrayObjects = function () {
  35826. if (this._vertexArrayObjects) {
  35827. for (var kind in this._vertexArrayObjects) {
  35828. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35829. }
  35830. this._vertexArrayObjects = {};
  35831. }
  35832. };
  35833. /**
  35834. * Free all associated resources
  35835. */
  35836. Geometry.prototype.dispose = function () {
  35837. var meshes = this._meshes;
  35838. var numOfMeshes = meshes.length;
  35839. var index;
  35840. for (index = 0; index < numOfMeshes; index++) {
  35841. this.releaseForMesh(meshes[index]);
  35842. }
  35843. this._meshes = [];
  35844. this._disposeVertexArrayObjects();
  35845. for (var kind in this._vertexBuffers) {
  35846. this._vertexBuffers[kind].dispose();
  35847. }
  35848. this._vertexBuffers = {};
  35849. this._totalVertices = 0;
  35850. if (this._indexBuffer) {
  35851. this._engine._releaseBuffer(this._indexBuffer);
  35852. }
  35853. this._indexBuffer = null;
  35854. this._indices = [];
  35855. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35856. this.delayLoadingFile = null;
  35857. this._delayLoadingFunction = null;
  35858. this._delayInfo = [];
  35859. this._boundingInfo = null;
  35860. this._scene.removeGeometry(this);
  35861. this._isDisposed = true;
  35862. };
  35863. /**
  35864. * Clone the current geometry into a new geometry
  35865. * @param id defines the unique ID of the new geometry
  35866. * @returns a new geometry object
  35867. */
  35868. Geometry.prototype.copy = function (id) {
  35869. var vertexData = new BABYLON.VertexData();
  35870. vertexData.indices = [];
  35871. var indices = this.getIndices();
  35872. if (indices) {
  35873. for (var index = 0; index < indices.length; index++) {
  35874. vertexData.indices.push(indices[index]);
  35875. }
  35876. }
  35877. var updatable = false;
  35878. var stopChecking = false;
  35879. var kind;
  35880. for (kind in this._vertexBuffers) {
  35881. // using slice() to make a copy of the array and not just reference it
  35882. var data = this.getVerticesData(kind);
  35883. if (data instanceof Float32Array) {
  35884. vertexData.set(new Float32Array(data), kind);
  35885. }
  35886. else {
  35887. vertexData.set(data.slice(0), kind);
  35888. }
  35889. if (!stopChecking) {
  35890. var vb = this.getVertexBuffer(kind);
  35891. if (vb) {
  35892. updatable = vb.isUpdatable();
  35893. stopChecking = !updatable;
  35894. }
  35895. }
  35896. }
  35897. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35898. geometry.delayLoadState = this.delayLoadState;
  35899. geometry.delayLoadingFile = this.delayLoadingFile;
  35900. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35901. for (kind in this._delayInfo) {
  35902. geometry._delayInfo = geometry._delayInfo || [];
  35903. geometry._delayInfo.push(kind);
  35904. }
  35905. // Bounding info
  35906. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35907. return geometry;
  35908. };
  35909. /**
  35910. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35911. * @return a JSON representation of the current geometry data (without the vertices data)
  35912. */
  35913. Geometry.prototype.serialize = function () {
  35914. var serializationObject = {};
  35915. serializationObject.id = this.id;
  35916. serializationObject.updatable = this._updatable;
  35917. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35918. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35919. }
  35920. return serializationObject;
  35921. };
  35922. Geometry.prototype.toNumberArray = function (origin) {
  35923. if (Array.isArray(origin)) {
  35924. return origin;
  35925. }
  35926. else {
  35927. return Array.prototype.slice.call(origin);
  35928. }
  35929. };
  35930. /**
  35931. * Serialize all vertices data into a JSON oject
  35932. * @returns a JSON representation of the current geometry data
  35933. */
  35934. Geometry.prototype.serializeVerticeData = function () {
  35935. var serializationObject = this.serialize();
  35936. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35937. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35938. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35939. serializationObject.positions._updatable = true;
  35940. }
  35941. }
  35942. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35943. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35944. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35945. serializationObject.normals._updatable = true;
  35946. }
  35947. }
  35948. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35949. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35950. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35951. serializationObject.tangets._updatable = true;
  35952. }
  35953. }
  35954. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35955. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35956. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35957. serializationObject.uvs._updatable = true;
  35958. }
  35959. }
  35960. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35961. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35962. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35963. serializationObject.uv2s._updatable = true;
  35964. }
  35965. }
  35966. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35967. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35968. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35969. serializationObject.uv3s._updatable = true;
  35970. }
  35971. }
  35972. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35973. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35974. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35975. serializationObject.uv4s._updatable = true;
  35976. }
  35977. }
  35978. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35979. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35980. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35981. serializationObject.uv5s._updatable = true;
  35982. }
  35983. }
  35984. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35985. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35986. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35987. serializationObject.uv6s._updatable = true;
  35988. }
  35989. }
  35990. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35991. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35992. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35993. serializationObject.colors._updatable = true;
  35994. }
  35995. }
  35996. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35997. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35998. serializationObject.matricesIndices._isExpanded = true;
  35999. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36000. serializationObject.matricesIndices._updatable = true;
  36001. }
  36002. }
  36003. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36004. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  36005. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36006. serializationObject.matricesWeights._updatable = true;
  36007. }
  36008. }
  36009. serializationObject.indices = this.toNumberArray(this.getIndices());
  36010. return serializationObject;
  36011. };
  36012. // Statics
  36013. /**
  36014. * Extracts a clone of a mesh geometry
  36015. * @param mesh defines the source mesh
  36016. * @param id defines the unique ID of the new geometry object
  36017. * @returns the new geometry object
  36018. */
  36019. Geometry.ExtractFromMesh = function (mesh, id) {
  36020. var geometry = mesh._geometry;
  36021. if (!geometry) {
  36022. return null;
  36023. }
  36024. return geometry.copy(id);
  36025. };
  36026. /**
  36027. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36028. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36029. * Be aware Math.random() could cause collisions, but:
  36030. * "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"
  36031. * @returns a string containing a new GUID
  36032. */
  36033. Geometry.RandomId = function () {
  36034. return BABYLON.Tools.RandomId();
  36035. };
  36036. /** @ignore */
  36037. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36038. var scene = mesh.getScene();
  36039. // Geometry
  36040. var geometryId = parsedGeometry.geometryId;
  36041. if (geometryId) {
  36042. var geometry = scene.getGeometryByID(geometryId);
  36043. if (geometry) {
  36044. geometry.applyToMesh(mesh);
  36045. }
  36046. }
  36047. else if (parsedGeometry instanceof ArrayBuffer) {
  36048. var binaryInfo = mesh._binaryInfo;
  36049. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36050. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36051. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36052. }
  36053. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36054. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36055. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36056. }
  36057. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36058. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36059. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36060. }
  36061. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36062. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36063. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36064. }
  36065. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36066. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36067. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36068. }
  36069. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36070. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36071. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36072. }
  36073. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36074. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36075. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36076. }
  36077. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36078. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36079. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36080. }
  36081. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36082. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36083. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36084. }
  36085. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36086. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36087. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36088. }
  36089. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36090. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36091. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36092. }
  36093. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36094. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36095. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36096. }
  36097. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36098. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36099. mesh.setIndices(indicesData, null);
  36100. }
  36101. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36102. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36103. mesh.subMeshes = [];
  36104. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36105. var materialIndex = subMeshesData[(i * 5) + 0];
  36106. var verticesStart = subMeshesData[(i * 5) + 1];
  36107. var verticesCount = subMeshesData[(i * 5) + 2];
  36108. var indexStart = subMeshesData[(i * 5) + 3];
  36109. var indexCount = subMeshesData[(i * 5) + 4];
  36110. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36111. }
  36112. }
  36113. }
  36114. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36115. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36116. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36117. if (parsedGeometry.tangents) {
  36118. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36119. }
  36120. if (parsedGeometry.uvs) {
  36121. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36122. }
  36123. if (parsedGeometry.uvs2) {
  36124. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36125. }
  36126. if (parsedGeometry.uvs3) {
  36127. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36128. }
  36129. if (parsedGeometry.uvs4) {
  36130. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36131. }
  36132. if (parsedGeometry.uvs5) {
  36133. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36134. }
  36135. if (parsedGeometry.uvs6) {
  36136. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36137. }
  36138. if (parsedGeometry.colors) {
  36139. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36140. }
  36141. if (parsedGeometry.matricesIndices) {
  36142. if (!parsedGeometry.matricesIndices._isExpanded) {
  36143. var floatIndices = [];
  36144. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36145. var matricesIndex = parsedGeometry.matricesIndices[i];
  36146. floatIndices.push(matricesIndex & 0x000000FF);
  36147. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36148. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36149. floatIndices.push(matricesIndex >> 24);
  36150. }
  36151. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36152. }
  36153. else {
  36154. delete parsedGeometry.matricesIndices._isExpanded;
  36155. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36156. }
  36157. }
  36158. if (parsedGeometry.matricesIndicesExtra) {
  36159. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36160. var floatIndices = [];
  36161. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36162. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36163. floatIndices.push(matricesIndex & 0x000000FF);
  36164. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36165. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36166. floatIndices.push(matricesIndex >> 24);
  36167. }
  36168. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36169. }
  36170. else {
  36171. delete parsedGeometry.matricesIndices._isExpanded;
  36172. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36173. }
  36174. }
  36175. if (parsedGeometry.matricesWeights) {
  36176. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36177. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36178. }
  36179. if (parsedGeometry.matricesWeightsExtra) {
  36180. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36181. }
  36182. mesh.setIndices(parsedGeometry.indices, null);
  36183. }
  36184. // SubMeshes
  36185. if (parsedGeometry.subMeshes) {
  36186. mesh.subMeshes = [];
  36187. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36188. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36189. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36190. }
  36191. }
  36192. // Flat shading
  36193. if (mesh._shouldGenerateFlatShading) {
  36194. mesh.convertToFlatShadedMesh();
  36195. delete mesh._shouldGenerateFlatShading;
  36196. }
  36197. // Update
  36198. mesh.computeWorldMatrix(true);
  36199. // Octree
  36200. var sceneOctree = scene.selectionOctree;
  36201. if (sceneOctree !== undefined && sceneOctree !== null) {
  36202. sceneOctree.addMesh(mesh);
  36203. }
  36204. };
  36205. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36206. var epsilon = 1e-3;
  36207. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36208. return;
  36209. }
  36210. var noInfluenceBoneIndex = 0.0;
  36211. if (parsedGeometry.skeletonId > -1) {
  36212. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36213. if (!skeleton) {
  36214. return;
  36215. }
  36216. noInfluenceBoneIndex = skeleton.bones.length;
  36217. }
  36218. else {
  36219. return;
  36220. }
  36221. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36222. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36223. var matricesWeights = parsedGeometry.matricesWeights;
  36224. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36225. var influencers = parsedGeometry.numBoneInfluencer;
  36226. var size = matricesWeights.length;
  36227. for (var i = 0; i < size; i += 4) {
  36228. var weight = 0.0;
  36229. var firstZeroWeight = -1;
  36230. for (var j = 0; j < 4; j++) {
  36231. var w = matricesWeights[i + j];
  36232. weight += w;
  36233. if (w < epsilon && firstZeroWeight < 0) {
  36234. firstZeroWeight = j;
  36235. }
  36236. }
  36237. if (matricesWeightsExtra) {
  36238. for (var j = 0; j < 4; j++) {
  36239. var w = matricesWeightsExtra[i + j];
  36240. weight += w;
  36241. if (w < epsilon && firstZeroWeight < 0) {
  36242. firstZeroWeight = j + 4;
  36243. }
  36244. }
  36245. }
  36246. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36247. firstZeroWeight = influencers - 1;
  36248. }
  36249. if (weight > epsilon) {
  36250. var mweight = 1.0 / weight;
  36251. for (var j = 0; j < 4; j++) {
  36252. matricesWeights[i + j] *= mweight;
  36253. }
  36254. if (matricesWeightsExtra) {
  36255. for (var j = 0; j < 4; j++) {
  36256. matricesWeightsExtra[i + j] *= mweight;
  36257. }
  36258. }
  36259. }
  36260. else {
  36261. if (firstZeroWeight >= 4) {
  36262. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36263. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36264. }
  36265. else {
  36266. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36267. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36268. }
  36269. }
  36270. }
  36271. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36272. if (parsedGeometry.matricesWeightsExtra) {
  36273. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36274. }
  36275. };
  36276. /**
  36277. * Create a new geometry from persisted data (Using .babylon file format)
  36278. * @param parsedVertexData defines the persisted data
  36279. * @param scene defines the hosting scene
  36280. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36281. * @returns the new geometry object
  36282. */
  36283. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36284. if (scene.getGeometryByID(parsedVertexData.id)) {
  36285. return null; // null since geometry could be something else than a box...
  36286. }
  36287. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36288. if (BABYLON.Tags) {
  36289. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36290. }
  36291. if (parsedVertexData.delayLoadingFile) {
  36292. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36293. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36294. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36295. geometry._delayInfo = [];
  36296. if (parsedVertexData.hasUVs) {
  36297. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36298. }
  36299. if (parsedVertexData.hasUVs2) {
  36300. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36301. }
  36302. if (parsedVertexData.hasUVs3) {
  36303. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36304. }
  36305. if (parsedVertexData.hasUVs4) {
  36306. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36307. }
  36308. if (parsedVertexData.hasUVs5) {
  36309. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36310. }
  36311. if (parsedVertexData.hasUVs6) {
  36312. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36313. }
  36314. if (parsedVertexData.hasColors) {
  36315. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36316. }
  36317. if (parsedVertexData.hasMatricesIndices) {
  36318. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36319. }
  36320. if (parsedVertexData.hasMatricesWeights) {
  36321. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36322. }
  36323. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36324. }
  36325. else {
  36326. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36327. }
  36328. scene.pushGeometry(geometry, true);
  36329. return geometry;
  36330. };
  36331. return Geometry;
  36332. }());
  36333. BABYLON.Geometry = Geometry;
  36334. // Primitives
  36335. /// Abstract class
  36336. /**
  36337. * Abstract class used to provide common services for all typed geometries
  36338. */
  36339. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36340. __extends(_PrimitiveGeometry, _super);
  36341. /**
  36342. * Creates a new typed geometry
  36343. * @param id defines the unique ID of the geometry
  36344. * @param scene defines the hosting scene
  36345. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36346. * @param mesh defines the hosting mesh (can be null)
  36347. */
  36348. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36349. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36350. if (mesh === void 0) { mesh = null; }
  36351. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36352. _this._canBeRegenerated = _canBeRegenerated;
  36353. _this._beingRegenerated = true;
  36354. _this.regenerate();
  36355. _this._beingRegenerated = false;
  36356. return _this;
  36357. }
  36358. /**
  36359. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36360. * @returns true if the geometry can be regenerated
  36361. */
  36362. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36363. return this._canBeRegenerated;
  36364. };
  36365. /**
  36366. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36367. */
  36368. _PrimitiveGeometry.prototype.regenerate = function () {
  36369. if (!this._canBeRegenerated) {
  36370. return;
  36371. }
  36372. this._beingRegenerated = true;
  36373. this.setAllVerticesData(this._regenerateVertexData(), false);
  36374. this._beingRegenerated = false;
  36375. };
  36376. /**
  36377. * Clone the geometry
  36378. * @param id defines the unique ID of the new geometry
  36379. * @returns the new geometry
  36380. */
  36381. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36382. return _super.prototype.copy.call(this, id);
  36383. };
  36384. // overrides
  36385. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36386. if (!this._beingRegenerated) {
  36387. return;
  36388. }
  36389. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36390. };
  36391. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36392. if (!this._beingRegenerated) {
  36393. return;
  36394. }
  36395. _super.prototype.setVerticesData.call(this, kind, data, false);
  36396. };
  36397. // to override
  36398. /** @ignore */
  36399. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36400. throw new Error("Abstract method");
  36401. };
  36402. _PrimitiveGeometry.prototype.copy = function (id) {
  36403. throw new Error("Must be overriden in sub-classes.");
  36404. };
  36405. _PrimitiveGeometry.prototype.serialize = function () {
  36406. var serializationObject = _super.prototype.serialize.call(this);
  36407. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36408. return serializationObject;
  36409. };
  36410. return _PrimitiveGeometry;
  36411. }(Geometry));
  36412. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36413. /**
  36414. * Creates a ribbon geometry
  36415. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36416. */
  36417. var RibbonGeometry = /** @class */ (function (_super) {
  36418. __extends(RibbonGeometry, _super);
  36419. /**
  36420. * Creates a ribbon geometry
  36421. * @param id defines the unique ID of the geometry
  36422. * @param scene defines the hosting scene
  36423. * @param pathArray defines the array of paths to use
  36424. * @param closeArray defines if the last path and the first path must be joined
  36425. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36426. * @param offset defines the offset between points
  36427. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36428. * @param mesh defines the hosting mesh (can be null)
  36429. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36430. */
  36431. function RibbonGeometry(id, scene,
  36432. /**
  36433. * Defines the array of paths to use
  36434. */
  36435. pathArray,
  36436. /**
  36437. * Defines if the last and first points of each path in your pathArray must be joined
  36438. */
  36439. closeArray,
  36440. /**
  36441. * Defines if the last and first points of each path in your pathArray must be joined
  36442. */
  36443. closePath,
  36444. /**
  36445. * Defines the offset between points
  36446. */
  36447. offset, canBeRegenerated, mesh,
  36448. /**
  36449. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36450. */
  36451. side) {
  36452. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36453. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36454. _this.pathArray = pathArray;
  36455. _this.closeArray = closeArray;
  36456. _this.closePath = closePath;
  36457. _this.offset = offset;
  36458. _this.side = side;
  36459. return _this;
  36460. }
  36461. /** @ignore */
  36462. RibbonGeometry.prototype._regenerateVertexData = function () {
  36463. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36464. };
  36465. RibbonGeometry.prototype.copy = function (id) {
  36466. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36467. };
  36468. return RibbonGeometry;
  36469. }(_PrimitiveGeometry));
  36470. BABYLON.RibbonGeometry = RibbonGeometry;
  36471. /**
  36472. * Creates a box geometry
  36473. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36474. */
  36475. var BoxGeometry = /** @class */ (function (_super) {
  36476. __extends(BoxGeometry, _super);
  36477. /**
  36478. * Creates a box geometry
  36479. * @param id defines the unique ID of the geometry
  36480. * @param scene defines the hosting scene
  36481. * @param size defines the zise of the box (width, height and depth are the same)
  36482. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36483. * @param mesh defines the hosting mesh (can be null)
  36484. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36485. */
  36486. function BoxGeometry(id, scene,
  36487. /**
  36488. * Defines the zise of the box (width, height and depth are the same)
  36489. */
  36490. size, canBeRegenerated, mesh,
  36491. /**
  36492. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36493. */
  36494. side) {
  36495. if (mesh === void 0) { mesh = null; }
  36496. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36497. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36498. _this.size = size;
  36499. _this.side = side;
  36500. return _this;
  36501. }
  36502. BoxGeometry.prototype._regenerateVertexData = function () {
  36503. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36504. };
  36505. BoxGeometry.prototype.copy = function (id) {
  36506. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36507. };
  36508. BoxGeometry.prototype.serialize = function () {
  36509. var serializationObject = _super.prototype.serialize.call(this);
  36510. serializationObject.size = this.size;
  36511. return serializationObject;
  36512. };
  36513. BoxGeometry.Parse = function (parsedBox, scene) {
  36514. if (scene.getGeometryByID(parsedBox.id)) {
  36515. return null; // null since geometry could be something else than a box...
  36516. }
  36517. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36518. if (BABYLON.Tags) {
  36519. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36520. }
  36521. scene.pushGeometry(box, true);
  36522. return box;
  36523. };
  36524. return BoxGeometry;
  36525. }(_PrimitiveGeometry));
  36526. BABYLON.BoxGeometry = BoxGeometry;
  36527. /**
  36528. * Creates a sphere geometry
  36529. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36530. */
  36531. var SphereGeometry = /** @class */ (function (_super) {
  36532. __extends(SphereGeometry, _super);
  36533. /**
  36534. * Create a new sphere geometry
  36535. * @param id defines the unique ID of the geometry
  36536. * @param scene defines the hosting scene
  36537. * @param segments defines the number of segments to use to create the sphere
  36538. * @param diameter defines the diameter of the sphere
  36539. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36540. * @param mesh defines the hosting mesh (can be null)
  36541. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36542. */
  36543. function SphereGeometry(id, scene,
  36544. /**
  36545. * Defines the number of segments to use to create the sphere
  36546. */
  36547. segments,
  36548. /**
  36549. * Defines the diameter of the sphere
  36550. */
  36551. diameter, canBeRegenerated, mesh,
  36552. /**
  36553. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36554. */
  36555. side) {
  36556. if (mesh === void 0) { mesh = null; }
  36557. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36558. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36559. _this.segments = segments;
  36560. _this.diameter = diameter;
  36561. _this.side = side;
  36562. return _this;
  36563. }
  36564. SphereGeometry.prototype._regenerateVertexData = function () {
  36565. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36566. };
  36567. SphereGeometry.prototype.copy = function (id) {
  36568. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36569. };
  36570. SphereGeometry.prototype.serialize = function () {
  36571. var serializationObject = _super.prototype.serialize.call(this);
  36572. serializationObject.segments = this.segments;
  36573. serializationObject.diameter = this.diameter;
  36574. return serializationObject;
  36575. };
  36576. SphereGeometry.Parse = function (parsedSphere, scene) {
  36577. if (scene.getGeometryByID(parsedSphere.id)) {
  36578. return null; // null since geometry could be something else than a sphere...
  36579. }
  36580. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36581. if (BABYLON.Tags) {
  36582. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36583. }
  36584. scene.pushGeometry(sphere, true);
  36585. return sphere;
  36586. };
  36587. return SphereGeometry;
  36588. }(_PrimitiveGeometry));
  36589. BABYLON.SphereGeometry = SphereGeometry;
  36590. /**
  36591. * Creates a disc geometry
  36592. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36593. */
  36594. var DiscGeometry = /** @class */ (function (_super) {
  36595. __extends(DiscGeometry, _super);
  36596. /**
  36597. * Creates a new disc geometry
  36598. * @param id defines the unique ID of the geometry
  36599. * @param scene defines the hosting scene
  36600. * @param radius defines the radius of the disc
  36601. * @param tessellation defines the tesselation factor to apply to the disc
  36602. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36603. * @param mesh defines the hosting mesh (can be null)
  36604. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36605. */
  36606. function DiscGeometry(id, scene,
  36607. /**
  36608. * Defines the radius of the disc
  36609. */
  36610. radius,
  36611. /**
  36612. * Defines the tesselation factor to apply to the disc
  36613. */
  36614. tessellation, canBeRegenerated, mesh,
  36615. /**
  36616. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36617. */
  36618. side) {
  36619. if (mesh === void 0) { mesh = null; }
  36620. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36621. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36622. _this.radius = radius;
  36623. _this.tessellation = tessellation;
  36624. _this.side = side;
  36625. return _this;
  36626. }
  36627. DiscGeometry.prototype._regenerateVertexData = function () {
  36628. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36629. };
  36630. DiscGeometry.prototype.copy = function (id) {
  36631. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36632. };
  36633. return DiscGeometry;
  36634. }(_PrimitiveGeometry));
  36635. BABYLON.DiscGeometry = DiscGeometry;
  36636. /**
  36637. * Creates a new cylinder geometry
  36638. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36639. */
  36640. var CylinderGeometry = /** @class */ (function (_super) {
  36641. __extends(CylinderGeometry, _super);
  36642. /**
  36643. * Creates a new cylinder geometry
  36644. * @param id defines the unique ID of the geometry
  36645. * @param scene defines the hosting scene
  36646. * @param height defines the height of the cylinder
  36647. * @param diameterTop defines the diameter of the cylinder's top cap
  36648. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36649. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36650. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36651. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36652. * @param mesh defines the hosting mesh (can be null)
  36653. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36654. */
  36655. function CylinderGeometry(id, scene,
  36656. /**
  36657. * Defines the height of the cylinder
  36658. */
  36659. height,
  36660. /**
  36661. * Defines the diameter of the cylinder's top cap
  36662. */
  36663. diameterTop,
  36664. /**
  36665. * Defines the diameter of the cylinder's bottom cap
  36666. */
  36667. diameterBottom,
  36668. /**
  36669. * Defines the tessellation factor to apply to the cylinder
  36670. */
  36671. tessellation,
  36672. /**
  36673. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36674. */
  36675. subdivisions, canBeRegenerated, mesh,
  36676. /**
  36677. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36678. */
  36679. side) {
  36680. if (subdivisions === void 0) { subdivisions = 1; }
  36681. if (mesh === void 0) { mesh = null; }
  36682. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36683. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36684. _this.height = height;
  36685. _this.diameterTop = diameterTop;
  36686. _this.diameterBottom = diameterBottom;
  36687. _this.tessellation = tessellation;
  36688. _this.subdivisions = subdivisions;
  36689. _this.side = side;
  36690. return _this;
  36691. }
  36692. CylinderGeometry.prototype._regenerateVertexData = function () {
  36693. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36694. };
  36695. CylinderGeometry.prototype.copy = function (id) {
  36696. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36697. };
  36698. CylinderGeometry.prototype.serialize = function () {
  36699. var serializationObject = _super.prototype.serialize.call(this);
  36700. serializationObject.height = this.height;
  36701. serializationObject.diameterTop = this.diameterTop;
  36702. serializationObject.diameterBottom = this.diameterBottom;
  36703. serializationObject.tessellation = this.tessellation;
  36704. return serializationObject;
  36705. };
  36706. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36707. if (scene.getGeometryByID(parsedCylinder.id)) {
  36708. return null; // null since geometry could be something else than a cylinder...
  36709. }
  36710. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36711. if (BABYLON.Tags) {
  36712. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36713. }
  36714. scene.pushGeometry(cylinder, true);
  36715. return cylinder;
  36716. };
  36717. return CylinderGeometry;
  36718. }(_PrimitiveGeometry));
  36719. BABYLON.CylinderGeometry = CylinderGeometry;
  36720. /**
  36721. * Creates a new torus geometry
  36722. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36723. */
  36724. var TorusGeometry = /** @class */ (function (_super) {
  36725. __extends(TorusGeometry, _super);
  36726. /**
  36727. * Creates a new torus geometry
  36728. * @param id defines the unique ID of the geometry
  36729. * @param scene defines the hosting scene
  36730. * @param diameter defines the diameter of the torus
  36731. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36732. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36733. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36734. * @param mesh defines the hosting mesh (can be null)
  36735. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36736. */
  36737. function TorusGeometry(id, scene,
  36738. /**
  36739. * Defines the diameter of the torus
  36740. */
  36741. diameter,
  36742. /**
  36743. * Defines the thickness of the torus (ie. internal diameter)
  36744. */
  36745. thickness,
  36746. /**
  36747. * Defines the tesselation factor to apply to the torus
  36748. */
  36749. tessellation, canBeRegenerated, mesh,
  36750. /**
  36751. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36752. */
  36753. side) {
  36754. if (mesh === void 0) { mesh = null; }
  36755. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36756. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36757. _this.diameter = diameter;
  36758. _this.thickness = thickness;
  36759. _this.tessellation = tessellation;
  36760. _this.side = side;
  36761. return _this;
  36762. }
  36763. TorusGeometry.prototype._regenerateVertexData = function () {
  36764. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36765. };
  36766. TorusGeometry.prototype.copy = function (id) {
  36767. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36768. };
  36769. TorusGeometry.prototype.serialize = function () {
  36770. var serializationObject = _super.prototype.serialize.call(this);
  36771. serializationObject.diameter = this.diameter;
  36772. serializationObject.thickness = this.thickness;
  36773. serializationObject.tessellation = this.tessellation;
  36774. return serializationObject;
  36775. };
  36776. TorusGeometry.Parse = function (parsedTorus, scene) {
  36777. if (scene.getGeometryByID(parsedTorus.id)) {
  36778. return null; // null since geometry could be something else than a torus...
  36779. }
  36780. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36781. if (BABYLON.Tags) {
  36782. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36783. }
  36784. scene.pushGeometry(torus, true);
  36785. return torus;
  36786. };
  36787. return TorusGeometry;
  36788. }(_PrimitiveGeometry));
  36789. BABYLON.TorusGeometry = TorusGeometry;
  36790. /**
  36791. * Creates a new ground geometry
  36792. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36793. */
  36794. var GroundGeometry = /** @class */ (function (_super) {
  36795. __extends(GroundGeometry, _super);
  36796. /**
  36797. * Creates a new ground geometry
  36798. * @param id defines the unique ID of the geometry
  36799. * @param scene defines the hosting scene
  36800. * @param width defines the width of the ground
  36801. * @param height defines the height of the ground
  36802. * @param subdivisions defines the subdivisions to apply to the ground
  36803. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36804. * @param mesh defines the hosting mesh (can be null)
  36805. */
  36806. function GroundGeometry(id, scene,
  36807. /**
  36808. * Defines the width of the ground
  36809. */
  36810. width,
  36811. /**
  36812. * Defines the height of the ground
  36813. */
  36814. height,
  36815. /**
  36816. * Defines the subdivisions to apply to the ground
  36817. */
  36818. subdivisions, canBeRegenerated, mesh) {
  36819. if (mesh === void 0) { mesh = null; }
  36820. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36821. _this.width = width;
  36822. _this.height = height;
  36823. _this.subdivisions = subdivisions;
  36824. return _this;
  36825. }
  36826. GroundGeometry.prototype._regenerateVertexData = function () {
  36827. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36828. };
  36829. GroundGeometry.prototype.copy = function (id) {
  36830. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36831. };
  36832. GroundGeometry.prototype.serialize = function () {
  36833. var serializationObject = _super.prototype.serialize.call(this);
  36834. serializationObject.width = this.width;
  36835. serializationObject.height = this.height;
  36836. serializationObject.subdivisions = this.subdivisions;
  36837. return serializationObject;
  36838. };
  36839. GroundGeometry.Parse = function (parsedGround, scene) {
  36840. if (scene.getGeometryByID(parsedGround.id)) {
  36841. return null; // null since geometry could be something else than a ground...
  36842. }
  36843. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36844. if (BABYLON.Tags) {
  36845. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36846. }
  36847. scene.pushGeometry(ground, true);
  36848. return ground;
  36849. };
  36850. return GroundGeometry;
  36851. }(_PrimitiveGeometry));
  36852. BABYLON.GroundGeometry = GroundGeometry;
  36853. /**
  36854. * Creates a tiled ground geometry
  36855. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36856. */
  36857. var TiledGroundGeometry = /** @class */ (function (_super) {
  36858. __extends(TiledGroundGeometry, _super);
  36859. /**
  36860. * Creates a tiled ground geometry
  36861. * @param id defines the unique ID of the geometry
  36862. * @param scene defines the hosting scene
  36863. * @param xmin defines the minimum value on X axis
  36864. * @param zmin defines the minimum value on Z axis
  36865. * @param xmax defines the maximum value on X axis
  36866. * @param zmax defines the maximum value on Z axis
  36867. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36868. * @param precision defines the precision to use when computing the tiles
  36869. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36870. * @param mesh defines the hosting mesh (can be null)
  36871. */
  36872. function TiledGroundGeometry(id, scene,
  36873. /**
  36874. * Defines the minimum value on X axis
  36875. */
  36876. xmin,
  36877. /**
  36878. * Defines the minimum value on Z axis
  36879. */
  36880. zmin,
  36881. /**
  36882. * Defines the maximum value on X axis
  36883. */
  36884. xmax,
  36885. /**
  36886. * Defines the maximum value on Z axis
  36887. */
  36888. zmax,
  36889. /**
  36890. * Defines the subdivisions to apply to the ground
  36891. */
  36892. subdivisions,
  36893. /**
  36894. * Defines the precision to use when computing the tiles
  36895. */
  36896. precision, canBeRegenerated, mesh) {
  36897. if (mesh === void 0) { mesh = null; }
  36898. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36899. _this.xmin = xmin;
  36900. _this.zmin = zmin;
  36901. _this.xmax = xmax;
  36902. _this.zmax = zmax;
  36903. _this.subdivisions = subdivisions;
  36904. _this.precision = precision;
  36905. return _this;
  36906. }
  36907. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36908. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36909. };
  36910. TiledGroundGeometry.prototype.copy = function (id) {
  36911. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36912. };
  36913. return TiledGroundGeometry;
  36914. }(_PrimitiveGeometry));
  36915. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36916. /**
  36917. * Creates a plane geometry
  36918. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36919. */
  36920. var PlaneGeometry = /** @class */ (function (_super) {
  36921. __extends(PlaneGeometry, _super);
  36922. /**
  36923. * Creates a plane geometry
  36924. * @param id defines the unique ID of the geometry
  36925. * @param scene defines the hosting scene
  36926. * @param size defines the size of the plane (width === height)
  36927. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36928. * @param mesh defines the hosting mesh (can be null)
  36929. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36930. */
  36931. function PlaneGeometry(id, scene,
  36932. /**
  36933. * Defines the size of the plane (width === height)
  36934. */
  36935. size, canBeRegenerated, mesh,
  36936. /**
  36937. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36938. */
  36939. side) {
  36940. if (mesh === void 0) { mesh = null; }
  36941. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36942. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36943. _this.size = size;
  36944. _this.side = side;
  36945. return _this;
  36946. }
  36947. PlaneGeometry.prototype._regenerateVertexData = function () {
  36948. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36949. };
  36950. PlaneGeometry.prototype.copy = function (id) {
  36951. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36952. };
  36953. PlaneGeometry.prototype.serialize = function () {
  36954. var serializationObject = _super.prototype.serialize.call(this);
  36955. serializationObject.size = this.size;
  36956. return serializationObject;
  36957. };
  36958. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36959. if (scene.getGeometryByID(parsedPlane.id)) {
  36960. return null; // null since geometry could be something else than a ground...
  36961. }
  36962. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36963. if (BABYLON.Tags) {
  36964. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36965. }
  36966. scene.pushGeometry(plane, true);
  36967. return plane;
  36968. };
  36969. return PlaneGeometry;
  36970. }(_PrimitiveGeometry));
  36971. BABYLON.PlaneGeometry = PlaneGeometry;
  36972. /**
  36973. * Creates a torus knot geometry
  36974. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36975. */
  36976. var TorusKnotGeometry = /** @class */ (function (_super) {
  36977. __extends(TorusKnotGeometry, _super);
  36978. /**
  36979. * Creates a torus knot geometry
  36980. * @param id defines the unique ID of the geometry
  36981. * @param scene defines the hosting scene
  36982. * @param radius defines the radius of the torus knot
  36983. * @param tube defines the thickness of the torus knot tube
  36984. * @param radialSegments defines the number of radial segments
  36985. * @param tubularSegments defines the number of tubular segments
  36986. * @param p defines the first number of windings
  36987. * @param q defines the second number of windings
  36988. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36989. * @param mesh defines the hosting mesh (can be null)
  36990. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36991. */
  36992. function TorusKnotGeometry(id, scene,
  36993. /**
  36994. * Defines the radius of the torus knot
  36995. */
  36996. radius,
  36997. /**
  36998. * Defines the thickness of the torus knot tube
  36999. */
  37000. tube,
  37001. /**
  37002. * Defines the number of radial segments
  37003. */
  37004. radialSegments,
  37005. /**
  37006. * Defines the number of tubular segments
  37007. */
  37008. tubularSegments,
  37009. /**
  37010. * Defines the first number of windings
  37011. */
  37012. p,
  37013. /**
  37014. * Defines the second number of windings
  37015. */
  37016. q, canBeRegenerated, mesh,
  37017. /**
  37018. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37019. */
  37020. side) {
  37021. if (mesh === void 0) { mesh = null; }
  37022. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37023. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37024. _this.radius = radius;
  37025. _this.tube = tube;
  37026. _this.radialSegments = radialSegments;
  37027. _this.tubularSegments = tubularSegments;
  37028. _this.p = p;
  37029. _this.q = q;
  37030. _this.side = side;
  37031. return _this;
  37032. }
  37033. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37034. 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 });
  37035. };
  37036. TorusKnotGeometry.prototype.copy = function (id) {
  37037. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37038. };
  37039. TorusKnotGeometry.prototype.serialize = function () {
  37040. var serializationObject = _super.prototype.serialize.call(this);
  37041. serializationObject.radius = this.radius;
  37042. serializationObject.tube = this.tube;
  37043. serializationObject.radialSegments = this.radialSegments;
  37044. serializationObject.tubularSegments = this.tubularSegments;
  37045. serializationObject.p = this.p;
  37046. serializationObject.q = this.q;
  37047. return serializationObject;
  37048. };
  37049. ;
  37050. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37051. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37052. return null; // null since geometry could be something else than a ground...
  37053. }
  37054. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37055. if (BABYLON.Tags) {
  37056. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37057. }
  37058. scene.pushGeometry(torusKnot, true);
  37059. return torusKnot;
  37060. };
  37061. return TorusKnotGeometry;
  37062. }(_PrimitiveGeometry));
  37063. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37064. //}
  37065. })(BABYLON || (BABYLON = {}));
  37066. //# sourceMappingURL=babylon.geometry.js.map
  37067. "use strict";
  37068. var BABYLON;
  37069. (function (BABYLON) {
  37070. /**
  37071. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37072. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37073. */
  37074. var PostProcessManager = /** @class */ (function () {
  37075. /**
  37076. * Creates a new instance of @see PostProcess
  37077. * @param scene The scene that the post process is associated with.
  37078. */
  37079. function PostProcessManager(scene) {
  37080. this._vertexBuffers = {};
  37081. this._scene = scene;
  37082. }
  37083. PostProcessManager.prototype._prepareBuffers = function () {
  37084. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37085. return;
  37086. }
  37087. // VBO
  37088. var vertices = [];
  37089. vertices.push(1, 1);
  37090. vertices.push(-1, 1);
  37091. vertices.push(-1, -1);
  37092. vertices.push(1, -1);
  37093. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37094. this._buildIndexBuffer();
  37095. };
  37096. PostProcessManager.prototype._buildIndexBuffer = function () {
  37097. // Indices
  37098. var indices = [];
  37099. indices.push(0);
  37100. indices.push(1);
  37101. indices.push(2);
  37102. indices.push(0);
  37103. indices.push(2);
  37104. indices.push(3);
  37105. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37106. };
  37107. /**
  37108. * Rebuilds the vertex buffers of the manager.
  37109. */
  37110. PostProcessManager.prototype._rebuild = function () {
  37111. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37112. if (!vb) {
  37113. return;
  37114. }
  37115. vb._rebuild();
  37116. this._buildIndexBuffer();
  37117. };
  37118. // Methods
  37119. /**
  37120. * Prepares a frame to be run through a post process.
  37121. * @param sourceTexture The input texture to the post procesess. (default: null)
  37122. * @param postProcesses An array of post processes to be run. (default: null)
  37123. * @returns True if the post processes were able to be run.
  37124. */
  37125. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37126. if (sourceTexture === void 0) { sourceTexture = null; }
  37127. if (postProcesses === void 0) { postProcesses = null; }
  37128. var camera = this._scene.activeCamera;
  37129. if (!camera) {
  37130. return false;
  37131. }
  37132. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37133. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37134. return false;
  37135. }
  37136. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37137. return true;
  37138. };
  37139. /**
  37140. * Manually render a set of post processes to a texture.
  37141. * @param postProcesses An array of post processes to be run.
  37142. * @param targetTexture The target texture to render to.
  37143. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37144. */
  37145. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37146. if (targetTexture === void 0) { targetTexture = null; }
  37147. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37148. var engine = this._scene.getEngine();
  37149. for (var index = 0; index < postProcesses.length; index++) {
  37150. if (index < postProcesses.length - 1) {
  37151. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37152. }
  37153. else {
  37154. if (targetTexture) {
  37155. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37156. }
  37157. else {
  37158. engine.restoreDefaultFramebuffer();
  37159. }
  37160. }
  37161. var pp = postProcesses[index];
  37162. var effect = pp.apply();
  37163. if (effect) {
  37164. pp.onBeforeRenderObservable.notifyObservers(effect);
  37165. // VBOs
  37166. this._prepareBuffers();
  37167. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37168. // Draw order
  37169. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37170. pp.onAfterRenderObservable.notifyObservers(effect);
  37171. }
  37172. }
  37173. // Restore depth buffer
  37174. engine.setDepthBuffer(true);
  37175. engine.setDepthWrite(true);
  37176. };
  37177. /**
  37178. * Finalize the result of the output of the postprocesses.
  37179. * @param doNotPresent If true the result will not be displayed to the screen.
  37180. * @param targetTexture The target texture to render to.
  37181. * @param faceIndex The index of the face to bind the target texture to.
  37182. * @param postProcesses The array of post processes to render.
  37183. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37184. */
  37185. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37186. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37187. var camera = this._scene.activeCamera;
  37188. if (!camera) {
  37189. return;
  37190. }
  37191. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37192. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37193. return;
  37194. }
  37195. var engine = this._scene.getEngine();
  37196. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37197. var pp = postProcesses[index];
  37198. if (index < len - 1) {
  37199. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37200. }
  37201. else {
  37202. if (targetTexture) {
  37203. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37204. }
  37205. else {
  37206. engine.restoreDefaultFramebuffer();
  37207. }
  37208. }
  37209. if (doNotPresent) {
  37210. break;
  37211. }
  37212. var effect = pp.apply();
  37213. if (effect) {
  37214. pp.onBeforeRenderObservable.notifyObservers(effect);
  37215. // VBOs
  37216. this._prepareBuffers();
  37217. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37218. // Draw order
  37219. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37220. pp.onAfterRenderObservable.notifyObservers(effect);
  37221. }
  37222. }
  37223. // Restore states
  37224. engine.setDepthBuffer(true);
  37225. engine.setDepthWrite(true);
  37226. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37227. };
  37228. /**
  37229. * Disposes of the post process manager.
  37230. */
  37231. PostProcessManager.prototype.dispose = function () {
  37232. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37233. if (buffer) {
  37234. buffer.dispose();
  37235. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37236. }
  37237. if (this._indexBuffer) {
  37238. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37239. this._indexBuffer = null;
  37240. }
  37241. };
  37242. return PostProcessManager;
  37243. }());
  37244. BABYLON.PostProcessManager = PostProcessManager;
  37245. })(BABYLON || (BABYLON = {}));
  37246. //# sourceMappingURL=babylon.postProcessManager.js.map
  37247. "use strict";
  37248. var BABYLON;
  37249. (function (BABYLON) {
  37250. /**
  37251. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37252. */
  37253. var PerformanceMonitor = /** @class */ (function () {
  37254. /**
  37255. * constructor
  37256. * @param frameSampleSize The number of samples required to saturate the sliding window
  37257. */
  37258. function PerformanceMonitor(frameSampleSize) {
  37259. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37260. this._enabled = true;
  37261. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37262. }
  37263. /**
  37264. * Samples current frame
  37265. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37266. */
  37267. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37268. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37269. if (!this._enabled)
  37270. return;
  37271. if (this._lastFrameTimeMs != null) {
  37272. var dt = timeMs - this._lastFrameTimeMs;
  37273. this._rollingFrameTime.add(dt);
  37274. }
  37275. this._lastFrameTimeMs = timeMs;
  37276. };
  37277. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37278. /**
  37279. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37280. * @return Average frame time in milliseconds
  37281. */
  37282. get: function () {
  37283. return this._rollingFrameTime.average;
  37284. },
  37285. enumerable: true,
  37286. configurable: true
  37287. });
  37288. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37289. /**
  37290. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37291. * @return Frame time variance in milliseconds squared
  37292. */
  37293. get: function () {
  37294. return this._rollingFrameTime.variance;
  37295. },
  37296. enumerable: true,
  37297. configurable: true
  37298. });
  37299. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37300. /**
  37301. * Returns the frame time of the most recent frame
  37302. * @return Frame time in milliseconds
  37303. */
  37304. get: function () {
  37305. return this._rollingFrameTime.history(0);
  37306. },
  37307. enumerable: true,
  37308. configurable: true
  37309. });
  37310. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37311. /**
  37312. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37313. * @return Framerate in frames per second
  37314. */
  37315. get: function () {
  37316. return 1000.0 / this._rollingFrameTime.average;
  37317. },
  37318. enumerable: true,
  37319. configurable: true
  37320. });
  37321. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37322. /**
  37323. * Returns the average framerate in frames per second using the most recent frame time
  37324. * @return Framerate in frames per second
  37325. */
  37326. get: function () {
  37327. var history = this._rollingFrameTime.history(0);
  37328. if (history === 0) {
  37329. return 0;
  37330. }
  37331. return 1000.0 / history;
  37332. },
  37333. enumerable: true,
  37334. configurable: true
  37335. });
  37336. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37337. /**
  37338. * Returns true if enough samples have been taken to completely fill the sliding window
  37339. * @return true if saturated
  37340. */
  37341. get: function () {
  37342. return this._rollingFrameTime.isSaturated();
  37343. },
  37344. enumerable: true,
  37345. configurable: true
  37346. });
  37347. /**
  37348. * Enables contributions to the sliding window sample set
  37349. */
  37350. PerformanceMonitor.prototype.enable = function () {
  37351. this._enabled = true;
  37352. };
  37353. /**
  37354. * Disables contributions to the sliding window sample set
  37355. * Samples will not be interpolated over the disabled period
  37356. */
  37357. PerformanceMonitor.prototype.disable = function () {
  37358. this._enabled = false;
  37359. //clear last sample to avoid interpolating over the disabled period when next enabled
  37360. this._lastFrameTimeMs = null;
  37361. };
  37362. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37363. /**
  37364. * Returns true if sampling is enabled
  37365. * @return true if enabled
  37366. */
  37367. get: function () {
  37368. return this._enabled;
  37369. },
  37370. enumerable: true,
  37371. configurable: true
  37372. });
  37373. /**
  37374. * Resets performance monitor
  37375. */
  37376. PerformanceMonitor.prototype.reset = function () {
  37377. //clear last sample to avoid interpolating over the disabled period when next enabled
  37378. this._lastFrameTimeMs = null;
  37379. //wipe record
  37380. this._rollingFrameTime.reset();
  37381. };
  37382. return PerformanceMonitor;
  37383. }());
  37384. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37385. /**
  37386. * RollingAverage
  37387. *
  37388. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37389. */
  37390. var RollingAverage = /** @class */ (function () {
  37391. /**
  37392. * constructor
  37393. * @param length The number of samples required to saturate the sliding window
  37394. */
  37395. function RollingAverage(length) {
  37396. this._samples = new Array(length);
  37397. this.reset();
  37398. }
  37399. /**
  37400. * Adds a sample to the sample set
  37401. * @param v The sample value
  37402. */
  37403. RollingAverage.prototype.add = function (v) {
  37404. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37405. var delta;
  37406. //we need to check if we've already wrapped round
  37407. if (this.isSaturated()) {
  37408. //remove bottom of stack from mean
  37409. var bottomValue = this._samples[this._pos];
  37410. delta = bottomValue - this.average;
  37411. this.average -= delta / (this._sampleCount - 1);
  37412. this._m2 -= delta * (bottomValue - this.average);
  37413. }
  37414. else {
  37415. this._sampleCount++;
  37416. }
  37417. //add new value to mean
  37418. delta = v - this.average;
  37419. this.average += delta / (this._sampleCount);
  37420. this._m2 += delta * (v - this.average);
  37421. //set the new variance
  37422. this.variance = this._m2 / (this._sampleCount - 1);
  37423. this._samples[this._pos] = v;
  37424. this._pos++;
  37425. this._pos %= this._samples.length; //positive wrap around
  37426. };
  37427. /**
  37428. * Returns previously added values or null if outside of history or outside the sliding window domain
  37429. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37430. * @return Value previously recorded with add() or null if outside of range
  37431. */
  37432. RollingAverage.prototype.history = function (i) {
  37433. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37434. return 0;
  37435. }
  37436. var i0 = this._wrapPosition(this._pos - 1.0);
  37437. return this._samples[this._wrapPosition(i0 - i)];
  37438. };
  37439. /**
  37440. * Returns true if enough samples have been taken to completely fill the sliding window
  37441. * @return true if sample-set saturated
  37442. */
  37443. RollingAverage.prototype.isSaturated = function () {
  37444. return this._sampleCount >= this._samples.length;
  37445. };
  37446. /**
  37447. * Resets the rolling average (equivalent to 0 samples taken so far)
  37448. */
  37449. RollingAverage.prototype.reset = function () {
  37450. this.average = 0;
  37451. this.variance = 0;
  37452. this._sampleCount = 0;
  37453. this._pos = 0;
  37454. this._m2 = 0;
  37455. };
  37456. /**
  37457. * Wraps a value around the sample range boundaries
  37458. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37459. * @return Wrapped position in sample range
  37460. */
  37461. RollingAverage.prototype._wrapPosition = function (i) {
  37462. var max = this._samples.length;
  37463. return ((i % max) + max) % max;
  37464. };
  37465. return RollingAverage;
  37466. }());
  37467. BABYLON.RollingAverage = RollingAverage;
  37468. })(BABYLON || (BABYLON = {}));
  37469. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37470. "use strict";
  37471. var BABYLON;
  37472. (function (BABYLON) {
  37473. /**
  37474. * This groups together the common properties used for image processing either in direct forward pass
  37475. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37476. * or not.
  37477. */
  37478. var ImageProcessingConfiguration = /** @class */ (function () {
  37479. function ImageProcessingConfiguration() {
  37480. /**
  37481. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37482. */
  37483. this.colorCurves = new BABYLON.ColorCurves();
  37484. this._colorCurvesEnabled = false;
  37485. this._colorGradingEnabled = false;
  37486. this._colorGradingWithGreenDepth = true;
  37487. this._colorGradingBGR = true;
  37488. this._exposure = 1.0;
  37489. this._toneMappingEnabled = false;
  37490. this._contrast = 1.0;
  37491. /**
  37492. * Vignette stretch size.
  37493. */
  37494. this.vignetteStretch = 0;
  37495. /**
  37496. * Vignette centre X Offset.
  37497. */
  37498. this.vignetteCentreX = 0;
  37499. /**
  37500. * Vignette centre Y Offset.
  37501. */
  37502. this.vignetteCentreY = 0;
  37503. /**
  37504. * Vignette weight or intensity of the vignette effect.
  37505. */
  37506. this.vignetteWeight = 1.5;
  37507. /**
  37508. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37509. * if vignetteEnabled is set to true.
  37510. */
  37511. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37512. /**
  37513. * Camera field of view used by the Vignette effect.
  37514. */
  37515. this.vignetteCameraFov = 0.5;
  37516. this._grainEnabled = false;
  37517. this._grainIntensity = 30;
  37518. this._grainAnimated = false;
  37519. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37520. this._vignetteEnabled = false;
  37521. this._applyByPostProcess = false;
  37522. this._isEnabled = true;
  37523. /**
  37524. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37525. * @type {BABYLON.Observable}
  37526. */
  37527. this.onUpdateParameters = new BABYLON.Observable();
  37528. }
  37529. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37530. /**
  37531. * Gets wether the color curves effect is enabled.
  37532. */
  37533. get: function () {
  37534. return this._colorCurvesEnabled;
  37535. },
  37536. /**
  37537. * Sets wether the color curves effect is enabled.
  37538. */
  37539. set: function (value) {
  37540. if (this._colorCurvesEnabled === value) {
  37541. return;
  37542. }
  37543. this._colorCurvesEnabled = value;
  37544. this._updateParameters();
  37545. },
  37546. enumerable: true,
  37547. configurable: true
  37548. });
  37549. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37550. /**
  37551. * Gets wether the color grading effect is enabled.
  37552. */
  37553. get: function () {
  37554. return this._colorGradingEnabled;
  37555. },
  37556. /**
  37557. * Sets wether the color grading effect is enabled.
  37558. */
  37559. set: function (value) {
  37560. if (this._colorGradingEnabled === value) {
  37561. return;
  37562. }
  37563. this._colorGradingEnabled = value;
  37564. this._updateParameters();
  37565. },
  37566. enumerable: true,
  37567. configurable: true
  37568. });
  37569. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37570. /**
  37571. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37572. */
  37573. get: function () {
  37574. return this._colorGradingWithGreenDepth;
  37575. },
  37576. /**
  37577. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37578. */
  37579. set: function (value) {
  37580. if (this._colorGradingWithGreenDepth === value) {
  37581. return;
  37582. }
  37583. this._colorGradingWithGreenDepth = value;
  37584. this._updateParameters();
  37585. },
  37586. enumerable: true,
  37587. configurable: true
  37588. });
  37589. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37590. /**
  37591. * Gets wether the color grading texture contains BGR values.
  37592. */
  37593. get: function () {
  37594. return this._colorGradingBGR;
  37595. },
  37596. /**
  37597. * Sets wether the color grading texture contains BGR values.
  37598. */
  37599. set: function (value) {
  37600. if (this._colorGradingBGR === value) {
  37601. return;
  37602. }
  37603. this._colorGradingBGR = value;
  37604. this._updateParameters();
  37605. },
  37606. enumerable: true,
  37607. configurable: true
  37608. });
  37609. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37610. /**
  37611. * Gets the Exposure used in the effect.
  37612. */
  37613. get: function () {
  37614. return this._exposure;
  37615. },
  37616. /**
  37617. * Sets the Exposure used in the effect.
  37618. */
  37619. set: function (value) {
  37620. if (this._exposure === value) {
  37621. return;
  37622. }
  37623. this._exposure = value;
  37624. this._updateParameters();
  37625. },
  37626. enumerable: true,
  37627. configurable: true
  37628. });
  37629. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37630. /**
  37631. * Gets wether the tone mapping effect is enabled.
  37632. */
  37633. get: function () {
  37634. return this._toneMappingEnabled;
  37635. },
  37636. /**
  37637. * Sets wether the tone mapping effect is enabled.
  37638. */
  37639. set: function (value) {
  37640. if (this._toneMappingEnabled === value) {
  37641. return;
  37642. }
  37643. this._toneMappingEnabled = value;
  37644. this._updateParameters();
  37645. },
  37646. enumerable: true,
  37647. configurable: true
  37648. });
  37649. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37650. /**
  37651. * Gets the contrast used in the effect.
  37652. */
  37653. get: function () {
  37654. return this._contrast;
  37655. },
  37656. /**
  37657. * Sets the contrast used in the effect.
  37658. */
  37659. set: function (value) {
  37660. if (this._contrast === value) {
  37661. return;
  37662. }
  37663. this._contrast = value;
  37664. this._updateParameters();
  37665. },
  37666. enumerable: true,
  37667. configurable: true
  37668. });
  37669. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37670. /**
  37671. * If the grain effect should be enabled.
  37672. */
  37673. get: function () {
  37674. return this._grainEnabled;
  37675. },
  37676. set: function (value) {
  37677. if (this._grainEnabled === value) {
  37678. return;
  37679. }
  37680. this._grainEnabled = value;
  37681. this._updateParameters();
  37682. },
  37683. enumerable: true,
  37684. configurable: true
  37685. });
  37686. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37687. /**
  37688. * Amount of grain to be applied by the grain effect.
  37689. */
  37690. get: function () {
  37691. return this._grainIntensity;
  37692. },
  37693. set: function (value) {
  37694. if (this._grainIntensity === value) {
  37695. return;
  37696. }
  37697. this._grainIntensity = value;
  37698. },
  37699. enumerable: true,
  37700. configurable: true
  37701. });
  37702. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37703. /**
  37704. * If the grain effect should be animated.
  37705. */
  37706. get: function () {
  37707. return this._grainAnimated;
  37708. },
  37709. set: function (value) {
  37710. if (this._grainAnimated === value) {
  37711. return;
  37712. }
  37713. this._grainAnimated = value;
  37714. this._updateParameters();
  37715. },
  37716. enumerable: true,
  37717. configurable: true
  37718. });
  37719. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37720. /**
  37721. * Gets the vignette blend mode allowing different kind of effect.
  37722. */
  37723. get: function () {
  37724. return this._vignetteBlendMode;
  37725. },
  37726. /**
  37727. * Sets the vignette blend mode allowing different kind of effect.
  37728. */
  37729. set: function (value) {
  37730. if (this._vignetteBlendMode === value) {
  37731. return;
  37732. }
  37733. this._vignetteBlendMode = value;
  37734. this._updateParameters();
  37735. },
  37736. enumerable: true,
  37737. configurable: true
  37738. });
  37739. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37740. /**
  37741. * Gets wether the vignette effect is enabled.
  37742. */
  37743. get: function () {
  37744. return this._vignetteEnabled;
  37745. },
  37746. /**
  37747. * Sets wether the vignette effect is enabled.
  37748. */
  37749. set: function (value) {
  37750. if (this._vignetteEnabled === value) {
  37751. return;
  37752. }
  37753. this._vignetteEnabled = value;
  37754. this._updateParameters();
  37755. },
  37756. enumerable: true,
  37757. configurable: true
  37758. });
  37759. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37760. /**
  37761. * Gets wether the image processing is applied through a post process or not.
  37762. */
  37763. get: function () {
  37764. return this._applyByPostProcess;
  37765. },
  37766. /**
  37767. * Sets wether the image processing is applied through a post process or not.
  37768. */
  37769. set: function (value) {
  37770. if (this._applyByPostProcess === value) {
  37771. return;
  37772. }
  37773. this._applyByPostProcess = value;
  37774. this._updateParameters();
  37775. },
  37776. enumerable: true,
  37777. configurable: true
  37778. });
  37779. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37780. /**
  37781. * Gets wether the image processing is enabled or not.
  37782. */
  37783. get: function () {
  37784. return this._isEnabled;
  37785. },
  37786. /**
  37787. * Sets wether the image processing is enabled or not.
  37788. */
  37789. set: function (value) {
  37790. if (this._isEnabled === value) {
  37791. return;
  37792. }
  37793. this._isEnabled = value;
  37794. this._updateParameters();
  37795. },
  37796. enumerable: true,
  37797. configurable: true
  37798. });
  37799. /**
  37800. * Method called each time the image processing information changes requires to recompile the effect.
  37801. */
  37802. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37803. this.onUpdateParameters.notifyObservers(this);
  37804. };
  37805. ImageProcessingConfiguration.prototype.getClassName = function () {
  37806. return "ImageProcessingConfiguration";
  37807. };
  37808. /**
  37809. * Prepare the list of uniforms associated with the Image Processing effects.
  37810. * @param uniformsList The list of uniforms used in the effect
  37811. * @param defines the list of defines currently in use
  37812. */
  37813. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37814. if (defines.EXPOSURE) {
  37815. uniforms.push("exposureLinear");
  37816. }
  37817. if (defines.CONTRAST) {
  37818. uniforms.push("contrast");
  37819. }
  37820. if (defines.COLORGRADING) {
  37821. uniforms.push("colorTransformSettings");
  37822. }
  37823. if (defines.VIGNETTE) {
  37824. uniforms.push("vInverseScreenSize");
  37825. uniforms.push("vignetteSettings1");
  37826. uniforms.push("vignetteSettings2");
  37827. }
  37828. if (defines.COLORCURVES) {
  37829. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37830. }
  37831. if (defines.GRAIN) {
  37832. uniforms.push("grainVarianceAmount");
  37833. uniforms.push("grainAnimatedSeed");
  37834. }
  37835. };
  37836. /**
  37837. * Prepare the list of samplers associated with the Image Processing effects.
  37838. * @param uniformsList The list of uniforms used in the effect
  37839. * @param defines the list of defines currently in use
  37840. */
  37841. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37842. if (defines.COLORGRADING) {
  37843. samplersList.push("txColorTransform");
  37844. }
  37845. };
  37846. /**
  37847. * Prepare the list of defines associated to the shader.
  37848. * @param defines the list of defines to complete
  37849. */
  37850. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37851. if (forPostProcess === void 0) { forPostProcess = false; }
  37852. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37853. defines.VIGNETTE = false;
  37854. defines.TONEMAPPING = false;
  37855. defines.CONTRAST = false;
  37856. defines.EXPOSURE = false;
  37857. defines.COLORCURVES = false;
  37858. defines.COLORGRADING = false;
  37859. defines.COLORGRADING3D = false;
  37860. defines.IMAGEPROCESSING = false;
  37861. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37862. return;
  37863. }
  37864. defines.VIGNETTE = this.vignetteEnabled;
  37865. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37866. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37867. defines.TONEMAPPING = this.toneMappingEnabled;
  37868. defines.CONTRAST = (this.contrast !== 1.0);
  37869. defines.EXPOSURE = (this.exposure !== 1.0);
  37870. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37871. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37872. if (defines.COLORGRADING) {
  37873. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37874. }
  37875. else {
  37876. defines.COLORGRADING3D = false;
  37877. }
  37878. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37879. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37880. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37881. defines.GRAIN = this.grainEnabled;
  37882. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37883. };
  37884. /**
  37885. * Returns true if all the image processing information are ready.
  37886. */
  37887. ImageProcessingConfiguration.prototype.isReady = function () {
  37888. // Color Grading texure can not be none blocking.
  37889. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37890. };
  37891. /**
  37892. * Binds the image processing to the shader.
  37893. * @param effect The effect to bind to
  37894. */
  37895. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37896. if (aspectRatio === void 0) { aspectRatio = 1; }
  37897. // Color Curves
  37898. if (this._colorCurvesEnabled && this.colorCurves) {
  37899. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37900. }
  37901. // Vignette
  37902. if (this._vignetteEnabled) {
  37903. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37904. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37905. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37906. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37907. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37908. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37909. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37910. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37911. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37912. var vignettePower = -2.0 * this.vignetteWeight;
  37913. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37914. }
  37915. // Exposure
  37916. effect.setFloat("exposureLinear", this.exposure);
  37917. // Contrast
  37918. effect.setFloat("contrast", this.contrast);
  37919. // Color transform settings
  37920. if (this.colorGradingTexture) {
  37921. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37922. var textureSize = this.colorGradingTexture.getSize().height;
  37923. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37924. 0.5 / textureSize, // textureOffset
  37925. textureSize, // textureSize
  37926. this.colorGradingTexture.level // weight
  37927. );
  37928. }
  37929. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37930. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37931. };
  37932. /**
  37933. * Clones the current image processing instance.
  37934. * @return The cloned image processing
  37935. */
  37936. ImageProcessingConfiguration.prototype.clone = function () {
  37937. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37938. };
  37939. /**
  37940. * Serializes the current image processing instance to a json representation.
  37941. * @return a JSON representation
  37942. */
  37943. ImageProcessingConfiguration.prototype.serialize = function () {
  37944. return BABYLON.SerializationHelper.Serialize(this);
  37945. };
  37946. /**
  37947. * Parses the image processing from a json representation.
  37948. * @param source the JSON source to parse
  37949. * @return The parsed image processing
  37950. */
  37951. ImageProcessingConfiguration.Parse = function (source) {
  37952. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37953. };
  37954. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37955. /**
  37956. * Used to apply the vignette as a mix with the pixel color.
  37957. */
  37958. get: function () {
  37959. return this._VIGNETTEMODE_MULTIPLY;
  37960. },
  37961. enumerable: true,
  37962. configurable: true
  37963. });
  37964. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37965. /**
  37966. * Used to apply the vignette as a replacement of the pixel color.
  37967. */
  37968. get: function () {
  37969. return this._VIGNETTEMODE_OPAQUE;
  37970. },
  37971. enumerable: true,
  37972. configurable: true
  37973. });
  37974. // Static constants associated to the image processing.
  37975. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37976. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37977. __decorate([
  37978. BABYLON.serializeAsColorCurves()
  37979. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37980. __decorate([
  37981. BABYLON.serialize()
  37982. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37983. __decorate([
  37984. BABYLON.serializeAsTexture()
  37985. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37986. __decorate([
  37987. BABYLON.serialize()
  37988. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37989. __decorate([
  37990. BABYLON.serialize()
  37991. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37992. __decorate([
  37993. BABYLON.serialize()
  37994. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37995. __decorate([
  37996. BABYLON.serialize()
  37997. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37998. __decorate([
  37999. BABYLON.serialize()
  38000. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  38001. __decorate([
  38002. BABYLON.serialize()
  38003. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  38004. __decorate([
  38005. BABYLON.serialize()
  38006. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  38007. __decorate([
  38008. BABYLON.serialize()
  38009. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  38010. __decorate([
  38011. BABYLON.serialize()
  38012. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  38013. __decorate([
  38014. BABYLON.serialize()
  38015. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  38016. __decorate([
  38017. BABYLON.serializeAsColor4()
  38018. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  38019. __decorate([
  38020. BABYLON.serialize()
  38021. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  38022. __decorate([
  38023. BABYLON.serialize()
  38024. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  38025. __decorate([
  38026. BABYLON.serialize()
  38027. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  38028. __decorate([
  38029. BABYLON.serialize()
  38030. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  38031. __decorate([
  38032. BABYLON.serialize()
  38033. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38034. __decorate([
  38035. BABYLON.serialize()
  38036. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38037. __decorate([
  38038. BABYLON.serialize()
  38039. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38040. __decorate([
  38041. BABYLON.serialize()
  38042. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38043. return ImageProcessingConfiguration;
  38044. }());
  38045. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38046. })(BABYLON || (BABYLON = {}));
  38047. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38048. "use strict";
  38049. var BABYLON;
  38050. (function (BABYLON) {
  38051. /**
  38052. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38053. * It can help converting any input color in a desired output one. This can then be used to create effects
  38054. * from sepia, black and white to sixties or futuristic rendering...
  38055. *
  38056. * The only supported format is currently 3dl.
  38057. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38058. */
  38059. var ColorGradingTexture = /** @class */ (function (_super) {
  38060. __extends(ColorGradingTexture, _super);
  38061. /**
  38062. * Instantiates a ColorGradingTexture from the following parameters.
  38063. *
  38064. * @param url The location of the color gradind data (currently only supporting 3dl)
  38065. * @param scene The scene the texture will be used in
  38066. */
  38067. function ColorGradingTexture(url, scene) {
  38068. var _this = _super.call(this, scene) || this;
  38069. if (!url) {
  38070. return _this;
  38071. }
  38072. _this._engine = scene.getEngine();
  38073. _this._textureMatrix = BABYLON.Matrix.Identity();
  38074. _this.name = url;
  38075. _this.url = url;
  38076. _this.hasAlpha = false;
  38077. _this.isCube = false;
  38078. _this.is3D = _this._engine.webGLVersion > 1;
  38079. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38080. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38081. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38082. _this.anisotropicFilteringLevel = 1;
  38083. _this._texture = _this._getFromCache(url, true);
  38084. if (!_this._texture) {
  38085. if (!scene.useDelayedTextureLoading) {
  38086. _this.loadTexture();
  38087. }
  38088. else {
  38089. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38090. }
  38091. }
  38092. return _this;
  38093. }
  38094. /**
  38095. * Returns the texture matrix used in most of the material.
  38096. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38097. */
  38098. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38099. return this._textureMatrix;
  38100. };
  38101. /**
  38102. * Occurs when the file being loaded is a .3dl LUT file.
  38103. */
  38104. ColorGradingTexture.prototype.load3dlTexture = function () {
  38105. var engine = this._engine;
  38106. var texture;
  38107. if (engine.webGLVersion === 1) {
  38108. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38109. }
  38110. else {
  38111. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38112. }
  38113. this._texture = texture;
  38114. var callback = function (text) {
  38115. if (typeof text !== "string") {
  38116. return;
  38117. }
  38118. var data = null;
  38119. var tempData = null;
  38120. var line;
  38121. var lines = text.split('\n');
  38122. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38123. var maxColor = 0;
  38124. for (var i = 0; i < lines.length; i++) {
  38125. line = lines[i];
  38126. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38127. continue;
  38128. if (line.indexOf('#') === 0)
  38129. continue;
  38130. var words = line.split(" ");
  38131. if (size === 0) {
  38132. // Number of space + one
  38133. size = words.length;
  38134. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38135. tempData = new Float32Array(size * size * size * 4);
  38136. continue;
  38137. }
  38138. if (size != 0) {
  38139. var r = Math.max(parseInt(words[0]), 0);
  38140. var g = Math.max(parseInt(words[1]), 0);
  38141. var b = Math.max(parseInt(words[2]), 0);
  38142. maxColor = Math.max(r, maxColor);
  38143. maxColor = Math.max(g, maxColor);
  38144. maxColor = Math.max(b, maxColor);
  38145. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38146. if (tempData) {
  38147. tempData[pixelStorageIndex + 0] = r;
  38148. tempData[pixelStorageIndex + 1] = g;
  38149. tempData[pixelStorageIndex + 2] = b;
  38150. }
  38151. pixelIndexSlice++;
  38152. if (pixelIndexSlice % size == 0) {
  38153. pixelIndexH++;
  38154. pixelIndexSlice = 0;
  38155. if (pixelIndexH % size == 0) {
  38156. pixelIndexW++;
  38157. pixelIndexH = 0;
  38158. }
  38159. }
  38160. }
  38161. }
  38162. if (tempData && data) {
  38163. for (var i = 0; i < tempData.length; i++) {
  38164. if (i > 0 && (i + 1) % 4 === 0) {
  38165. data[i] = 255;
  38166. }
  38167. else {
  38168. var value = tempData[i];
  38169. data[i] = (value / maxColor * 255);
  38170. }
  38171. }
  38172. }
  38173. if (texture.is3D) {
  38174. texture.updateSize(size, size, size);
  38175. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38176. }
  38177. else {
  38178. texture.updateSize(size * size, size);
  38179. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38180. }
  38181. };
  38182. var scene = this.getScene();
  38183. if (scene) {
  38184. scene._loadFile(this.url, callback);
  38185. }
  38186. else {
  38187. this._engine._loadFile(this.url, callback);
  38188. }
  38189. return this._texture;
  38190. };
  38191. /**
  38192. * Starts the loading process of the texture.
  38193. */
  38194. ColorGradingTexture.prototype.loadTexture = function () {
  38195. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38196. this.load3dlTexture();
  38197. }
  38198. };
  38199. /**
  38200. * Clones the color gradind texture.
  38201. */
  38202. ColorGradingTexture.prototype.clone = function () {
  38203. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38204. // Base texture
  38205. newTexture.level = this.level;
  38206. return newTexture;
  38207. };
  38208. /**
  38209. * Called during delayed load for textures.
  38210. */
  38211. ColorGradingTexture.prototype.delayLoad = function () {
  38212. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38213. return;
  38214. }
  38215. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38216. this._texture = this._getFromCache(this.url, true);
  38217. if (!this._texture) {
  38218. this.loadTexture();
  38219. }
  38220. };
  38221. /**
  38222. * Parses a color grading texture serialized by Babylon.
  38223. * @param parsedTexture The texture information being parsedTexture
  38224. * @param scene The scene to load the texture in
  38225. * @param rootUrl The root url of the data assets to load
  38226. * @return A color gradind texture
  38227. */
  38228. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38229. var texture = null;
  38230. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38231. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38232. texture.name = parsedTexture.name;
  38233. texture.level = parsedTexture.level;
  38234. }
  38235. return texture;
  38236. };
  38237. /**
  38238. * Serializes the LUT texture to json format.
  38239. */
  38240. ColorGradingTexture.prototype.serialize = function () {
  38241. if (!this.name) {
  38242. return null;
  38243. }
  38244. var serializationObject = {};
  38245. serializationObject.name = this.name;
  38246. serializationObject.level = this.level;
  38247. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38248. return serializationObject;
  38249. };
  38250. /**
  38251. * Empty line regex stored for GC.
  38252. */
  38253. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38254. return ColorGradingTexture;
  38255. }(BABYLON.BaseTexture));
  38256. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38257. })(BABYLON || (BABYLON = {}));
  38258. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38259. "use strict";
  38260. var BABYLON;
  38261. (function (BABYLON) {
  38262. /**
  38263. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38264. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38265. * 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;
  38266. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38267. */
  38268. var ColorCurves = /** @class */ (function () {
  38269. function ColorCurves() {
  38270. this._dirty = true;
  38271. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38272. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38273. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38274. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38275. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38276. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38277. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38278. this._globalHue = 30;
  38279. this._globalDensity = 0;
  38280. this._globalSaturation = 0;
  38281. this._globalExposure = 0;
  38282. this._highlightsHue = 30;
  38283. this._highlightsDensity = 0;
  38284. this._highlightsSaturation = 0;
  38285. this._highlightsExposure = 0;
  38286. this._midtonesHue = 30;
  38287. this._midtonesDensity = 0;
  38288. this._midtonesSaturation = 0;
  38289. this._midtonesExposure = 0;
  38290. this._shadowsHue = 30;
  38291. this._shadowsDensity = 0;
  38292. this._shadowsSaturation = 0;
  38293. this._shadowsExposure = 0;
  38294. }
  38295. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38296. /**
  38297. * Gets the global Hue value.
  38298. * 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).
  38299. */
  38300. get: function () {
  38301. return this._globalHue;
  38302. },
  38303. /**
  38304. * Sets the global Hue value.
  38305. * 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).
  38306. */
  38307. set: function (value) {
  38308. this._globalHue = value;
  38309. this._dirty = true;
  38310. },
  38311. enumerable: true,
  38312. configurable: true
  38313. });
  38314. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38315. /**
  38316. * Gets the global Density value.
  38317. * 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.
  38318. * Values less than zero provide a filter of opposite hue.
  38319. */
  38320. get: function () {
  38321. return this._globalDensity;
  38322. },
  38323. /**
  38324. * Sets the global Density value.
  38325. * 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.
  38326. * Values less than zero provide a filter of opposite hue.
  38327. */
  38328. set: function (value) {
  38329. this._globalDensity = value;
  38330. this._dirty = true;
  38331. },
  38332. enumerable: true,
  38333. configurable: true
  38334. });
  38335. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38336. /**
  38337. * Gets the global Saturation value.
  38338. * 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.
  38339. */
  38340. get: function () {
  38341. return this._globalSaturation;
  38342. },
  38343. /**
  38344. * Sets the global Saturation value.
  38345. * 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.
  38346. */
  38347. set: function (value) {
  38348. this._globalSaturation = value;
  38349. this._dirty = true;
  38350. },
  38351. enumerable: true,
  38352. configurable: true
  38353. });
  38354. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38355. /**
  38356. * Gets the highlights Hue value.
  38357. * 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).
  38358. */
  38359. get: function () {
  38360. return this._highlightsHue;
  38361. },
  38362. /**
  38363. * Sets the highlights Hue value.
  38364. * 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).
  38365. */
  38366. set: function (value) {
  38367. this._highlightsHue = value;
  38368. this._dirty = true;
  38369. },
  38370. enumerable: true,
  38371. configurable: true
  38372. });
  38373. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38374. /**
  38375. * Gets the highlights Density value.
  38376. * 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.
  38377. * Values less than zero provide a filter of opposite hue.
  38378. */
  38379. get: function () {
  38380. return this._highlightsDensity;
  38381. },
  38382. /**
  38383. * Sets the highlights Density value.
  38384. * 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.
  38385. * Values less than zero provide a filter of opposite hue.
  38386. */
  38387. set: function (value) {
  38388. this._highlightsDensity = value;
  38389. this._dirty = true;
  38390. },
  38391. enumerable: true,
  38392. configurable: true
  38393. });
  38394. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38395. /**
  38396. * Gets the highlights Saturation value.
  38397. * 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.
  38398. */
  38399. get: function () {
  38400. return this._highlightsSaturation;
  38401. },
  38402. /**
  38403. * Sets the highlights Saturation value.
  38404. * 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.
  38405. */
  38406. set: function (value) {
  38407. this._highlightsSaturation = value;
  38408. this._dirty = true;
  38409. },
  38410. enumerable: true,
  38411. configurable: true
  38412. });
  38413. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38414. /**
  38415. * Gets the highlights Exposure value.
  38416. * 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.
  38417. */
  38418. get: function () {
  38419. return this._highlightsExposure;
  38420. },
  38421. /**
  38422. * Sets the highlights Exposure value.
  38423. * 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.
  38424. */
  38425. set: function (value) {
  38426. this._highlightsExposure = value;
  38427. this._dirty = true;
  38428. },
  38429. enumerable: true,
  38430. configurable: true
  38431. });
  38432. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38433. /**
  38434. * Gets the midtones Hue value.
  38435. * 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).
  38436. */
  38437. get: function () {
  38438. return this._midtonesHue;
  38439. },
  38440. /**
  38441. * Sets the midtones Hue value.
  38442. * 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).
  38443. */
  38444. set: function (value) {
  38445. this._midtonesHue = value;
  38446. this._dirty = true;
  38447. },
  38448. enumerable: true,
  38449. configurable: true
  38450. });
  38451. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38452. /**
  38453. * Gets the midtones Density value.
  38454. * 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.
  38455. * Values less than zero provide a filter of opposite hue.
  38456. */
  38457. get: function () {
  38458. return this._midtonesDensity;
  38459. },
  38460. /**
  38461. * Sets the midtones Density value.
  38462. * 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.
  38463. * Values less than zero provide a filter of opposite hue.
  38464. */
  38465. set: function (value) {
  38466. this._midtonesDensity = value;
  38467. this._dirty = true;
  38468. },
  38469. enumerable: true,
  38470. configurable: true
  38471. });
  38472. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38473. /**
  38474. * Gets the midtones Saturation value.
  38475. * 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.
  38476. */
  38477. get: function () {
  38478. return this._midtonesSaturation;
  38479. },
  38480. /**
  38481. * Sets the midtones Saturation value.
  38482. * 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.
  38483. */
  38484. set: function (value) {
  38485. this._midtonesSaturation = value;
  38486. this._dirty = true;
  38487. },
  38488. enumerable: true,
  38489. configurable: true
  38490. });
  38491. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38492. /**
  38493. * Gets the midtones Exposure value.
  38494. * 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.
  38495. */
  38496. get: function () {
  38497. return this._midtonesExposure;
  38498. },
  38499. /**
  38500. * Sets the midtones Exposure value.
  38501. * 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.
  38502. */
  38503. set: function (value) {
  38504. this._midtonesExposure = value;
  38505. this._dirty = true;
  38506. },
  38507. enumerable: true,
  38508. configurable: true
  38509. });
  38510. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38511. /**
  38512. * Gets the shadows Hue value.
  38513. * 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).
  38514. */
  38515. get: function () {
  38516. return this._shadowsHue;
  38517. },
  38518. /**
  38519. * Sets the shadows Hue value.
  38520. * 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).
  38521. */
  38522. set: function (value) {
  38523. this._shadowsHue = value;
  38524. this._dirty = true;
  38525. },
  38526. enumerable: true,
  38527. configurable: true
  38528. });
  38529. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38530. /**
  38531. * Gets the shadows Density value.
  38532. * 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.
  38533. * Values less than zero provide a filter of opposite hue.
  38534. */
  38535. get: function () {
  38536. return this._shadowsDensity;
  38537. },
  38538. /**
  38539. * Sets the shadows Density value.
  38540. * 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.
  38541. * Values less than zero provide a filter of opposite hue.
  38542. */
  38543. set: function (value) {
  38544. this._shadowsDensity = value;
  38545. this._dirty = true;
  38546. },
  38547. enumerable: true,
  38548. configurable: true
  38549. });
  38550. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38551. /**
  38552. * Gets the shadows Saturation value.
  38553. * 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.
  38554. */
  38555. get: function () {
  38556. return this._shadowsSaturation;
  38557. },
  38558. /**
  38559. * Sets the shadows Saturation value.
  38560. * 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.
  38561. */
  38562. set: function (value) {
  38563. this._shadowsSaturation = value;
  38564. this._dirty = true;
  38565. },
  38566. enumerable: true,
  38567. configurable: true
  38568. });
  38569. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38570. /**
  38571. * Gets the shadows Exposure value.
  38572. * 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.
  38573. */
  38574. get: function () {
  38575. return this._shadowsExposure;
  38576. },
  38577. /**
  38578. * Sets the shadows Exposure value.
  38579. * 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.
  38580. */
  38581. set: function (value) {
  38582. this._shadowsExposure = value;
  38583. this._dirty = true;
  38584. },
  38585. enumerable: true,
  38586. configurable: true
  38587. });
  38588. ColorCurves.prototype.getClassName = function () {
  38589. return "ColorCurves";
  38590. };
  38591. /**
  38592. * Binds the color curves to the shader.
  38593. * @param colorCurves The color curve to bind
  38594. * @param effect The effect to bind to
  38595. */
  38596. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38597. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38598. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38599. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38600. if (colorCurves._dirty) {
  38601. colorCurves._dirty = false;
  38602. // Fill in global info.
  38603. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38604. // Compute highlights info.
  38605. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38606. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38607. // Compute midtones info.
  38608. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38609. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38610. // Compute shadows info.
  38611. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38612. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38613. // Compute deltas (neutral is midtones).
  38614. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38615. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38616. }
  38617. if (effect) {
  38618. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38619. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38620. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38621. }
  38622. };
  38623. /**
  38624. * Prepare the list of uniforms associated with the ColorCurves effects.
  38625. * @param uniformsList The list of uniforms used in the effect
  38626. */
  38627. ColorCurves.PrepareUniforms = function (uniformsList) {
  38628. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38629. };
  38630. /**
  38631. * Returns color grading data based on a hue, density, saturation and exposure value.
  38632. * @param filterHue The hue of the color filter.
  38633. * @param filterDensity The density of the color filter.
  38634. * @param saturation The saturation.
  38635. * @param exposure The exposure.
  38636. * @param result The result data container.
  38637. */
  38638. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38639. if (hue == null) {
  38640. return;
  38641. }
  38642. hue = ColorCurves.clamp(hue, 0, 360);
  38643. density = ColorCurves.clamp(density, -100, 100);
  38644. saturation = ColorCurves.clamp(saturation, -100, 100);
  38645. exposure = ColorCurves.clamp(exposure, -100, 100);
  38646. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38647. // so that the maximum filter density is only 50% control. This provides fine control
  38648. // for small values and reasonable range.
  38649. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38650. density *= 0.5;
  38651. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38652. if (density < 0) {
  38653. density *= -1;
  38654. hue = (hue + 180) % 360;
  38655. }
  38656. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38657. result.scaleToRef(2, result);
  38658. result.a = 1 + 0.01 * saturation;
  38659. };
  38660. /**
  38661. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38662. * @param value The input slider value in range [-100,100].
  38663. * @returns Adjusted value.
  38664. */
  38665. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38666. value /= 100;
  38667. var x = Math.abs(value);
  38668. x = Math.pow(x, 2);
  38669. if (value < 0) {
  38670. x *= -1;
  38671. }
  38672. x *= 100;
  38673. return x;
  38674. };
  38675. /**
  38676. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38677. * @param hue The hue (H) input.
  38678. * @param saturation The saturation (S) input.
  38679. * @param brightness The brightness (B) input.
  38680. * @result An RGBA color represented as Vector4.
  38681. */
  38682. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38683. var h = ColorCurves.clamp(hue, 0, 360);
  38684. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38685. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38686. if (s === 0) {
  38687. result.r = v;
  38688. result.g = v;
  38689. result.b = v;
  38690. }
  38691. else {
  38692. // sector 0 to 5
  38693. h /= 60;
  38694. var i = Math.floor(h);
  38695. // fractional part of h
  38696. var f = h - i;
  38697. var p = v * (1 - s);
  38698. var q = v * (1 - s * f);
  38699. var t = v * (1 - s * (1 - f));
  38700. switch (i) {
  38701. case 0:
  38702. result.r = v;
  38703. result.g = t;
  38704. result.b = p;
  38705. break;
  38706. case 1:
  38707. result.r = q;
  38708. result.g = v;
  38709. result.b = p;
  38710. break;
  38711. case 2:
  38712. result.r = p;
  38713. result.g = v;
  38714. result.b = t;
  38715. break;
  38716. case 3:
  38717. result.r = p;
  38718. result.g = q;
  38719. result.b = v;
  38720. break;
  38721. case 4:
  38722. result.r = t;
  38723. result.g = p;
  38724. result.b = v;
  38725. break;
  38726. default:// case 5:
  38727. result.r = v;
  38728. result.g = p;
  38729. result.b = q;
  38730. break;
  38731. }
  38732. }
  38733. result.a = 1;
  38734. };
  38735. /**
  38736. * Returns a value clamped between min and max
  38737. * @param value The value to clamp
  38738. * @param min The minimum of value
  38739. * @param max The maximum of value
  38740. * @returns The clamped value.
  38741. */
  38742. ColorCurves.clamp = function (value, min, max) {
  38743. return Math.min(Math.max(value, min), max);
  38744. };
  38745. /**
  38746. * Clones the current color curve instance.
  38747. * @return The cloned curves
  38748. */
  38749. ColorCurves.prototype.clone = function () {
  38750. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38751. };
  38752. /**
  38753. * Serializes the current color curve instance to a json representation.
  38754. * @return a JSON representation
  38755. */
  38756. ColorCurves.prototype.serialize = function () {
  38757. return BABYLON.SerializationHelper.Serialize(this);
  38758. };
  38759. /**
  38760. * Parses the color curve from a json representation.
  38761. * @param source the JSON source to parse
  38762. * @return The parsed curves
  38763. */
  38764. ColorCurves.Parse = function (source) {
  38765. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38766. };
  38767. __decorate([
  38768. BABYLON.serialize()
  38769. ], ColorCurves.prototype, "_globalHue", void 0);
  38770. __decorate([
  38771. BABYLON.serialize()
  38772. ], ColorCurves.prototype, "_globalDensity", void 0);
  38773. __decorate([
  38774. BABYLON.serialize()
  38775. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38776. __decorate([
  38777. BABYLON.serialize()
  38778. ], ColorCurves.prototype, "_globalExposure", void 0);
  38779. __decorate([
  38780. BABYLON.serialize()
  38781. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38782. __decorate([
  38783. BABYLON.serialize()
  38784. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38785. __decorate([
  38786. BABYLON.serialize()
  38787. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38788. __decorate([
  38789. BABYLON.serialize()
  38790. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38791. __decorate([
  38792. BABYLON.serialize()
  38793. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38794. __decorate([
  38795. BABYLON.serialize()
  38796. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38797. __decorate([
  38798. BABYLON.serialize()
  38799. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38800. __decorate([
  38801. BABYLON.serialize()
  38802. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38803. return ColorCurves;
  38804. }());
  38805. BABYLON.ColorCurves = ColorCurves;
  38806. })(BABYLON || (BABYLON = {}));
  38807. //# sourceMappingURL=babylon.colorCurves.js.map
  38808. "use strict";
  38809. //# sourceMappingURL=babylon.behavior.js.map
  38810. "use strict";
  38811. var BABYLON;
  38812. (function (BABYLON) {
  38813. /**
  38814. * "Static Class" containing the most commonly used helper while dealing with material for
  38815. * rendering purpose.
  38816. *
  38817. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38818. *
  38819. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38820. */
  38821. var MaterialHelper = /** @class */ (function () {
  38822. function MaterialHelper() {
  38823. }
  38824. /**
  38825. * Bind the current view position to an effect.
  38826. * @param effect The effect to be bound
  38827. * @param scene The scene the eyes position is used from
  38828. */
  38829. MaterialHelper.BindEyePosition = function (effect, scene) {
  38830. if (scene._forcedViewPosition) {
  38831. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38832. return;
  38833. }
  38834. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38835. };
  38836. /**
  38837. * Helps preparing the defines values about the UVs in used in the effect.
  38838. * UVs are shared as much as we can accross chanels in the shaders.
  38839. * @param texture The texture we are preparing the UVs for
  38840. * @param defines The defines to update
  38841. * @param key The chanel key "diffuse", "specular"... used in the shader
  38842. */
  38843. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38844. defines._needUVs = true;
  38845. defines[key] = true;
  38846. if (texture.getTextureMatrix().isIdentity(true)) {
  38847. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38848. if (texture.coordinatesIndex === 0) {
  38849. defines["MAINUV1"] = true;
  38850. }
  38851. else {
  38852. defines["MAINUV2"] = true;
  38853. }
  38854. }
  38855. else {
  38856. defines[key + "DIRECTUV"] = 0;
  38857. }
  38858. };
  38859. /**
  38860. * Binds a texture matrix value to its corrsponding uniform
  38861. * @param texture The texture to bind the matrix for
  38862. * @param uniformBuffer The uniform buffer receivin the data
  38863. * @param key The chanel key "diffuse", "specular"... used in the shader
  38864. */
  38865. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38866. var matrix = texture.getTextureMatrix();
  38867. if (!matrix.isIdentity(true)) {
  38868. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38869. }
  38870. };
  38871. /**
  38872. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38873. * @param mesh defines the current mesh
  38874. * @param scene defines the current scene
  38875. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38876. * @param pointsCloud defines if point cloud rendering has to be turned on
  38877. * @param fogEnabled defines if fog has to be turned on
  38878. * @param alphaTest defines if alpha testing has to be turned on
  38879. * @param defines defines the current list of defines
  38880. */
  38881. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38882. if (defines._areMiscDirty) {
  38883. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38884. defines["POINTSIZE"] = pointsCloud;
  38885. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38886. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38887. defines["ALPHATEST"] = alphaTest;
  38888. }
  38889. };
  38890. /**
  38891. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38892. * @param scene defines the current scene
  38893. * @param engine defines the current engine
  38894. * @param defines specifies the list of active defines
  38895. * @param useInstances defines if instances have to be turned on
  38896. * @param useClipPlane defines if clip plane have to be turned on
  38897. */
  38898. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38899. if (useClipPlane === void 0) { useClipPlane = null; }
  38900. var changed = false;
  38901. if (useClipPlane == null) {
  38902. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38903. }
  38904. if (defines["CLIPPLANE"] !== useClipPlane) {
  38905. defines["CLIPPLANE"] = useClipPlane;
  38906. changed = true;
  38907. }
  38908. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38909. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38910. changed = true;
  38911. }
  38912. if (defines["INSTANCES"] !== useInstances) {
  38913. defines["INSTANCES"] = useInstances;
  38914. changed = true;
  38915. }
  38916. if (changed) {
  38917. defines.markAsUnprocessed();
  38918. }
  38919. };
  38920. /**
  38921. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38922. * @param mesh The mesh containing the geometry data we will draw
  38923. * @param defines The defines to update
  38924. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38925. * @param useBones Precise whether bones should be used or not (override mesh info)
  38926. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38927. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38928. * @returns false if defines are considered not dirty and have not been checked
  38929. */
  38930. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38931. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38932. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38933. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38934. return false;
  38935. }
  38936. defines._normals = defines._needNormals;
  38937. defines._uvs = defines._needUVs;
  38938. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38939. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38940. defines["TANGENT"] = true;
  38941. }
  38942. if (defines._needUVs) {
  38943. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38944. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38945. }
  38946. else {
  38947. defines["UV1"] = false;
  38948. defines["UV2"] = false;
  38949. }
  38950. if (useVertexColor) {
  38951. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38952. defines["VERTEXCOLOR"] = hasVertexColors;
  38953. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38954. }
  38955. if (useBones) {
  38956. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38957. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38958. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38959. }
  38960. else {
  38961. defines["NUM_BONE_INFLUENCERS"] = 0;
  38962. defines["BonesPerMesh"] = 0;
  38963. }
  38964. }
  38965. if (useMorphTargets) {
  38966. var manager = mesh.morphTargetManager;
  38967. if (manager) {
  38968. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38969. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38970. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38971. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38972. }
  38973. else {
  38974. defines["MORPHTARGETS_TANGENT"] = false;
  38975. defines["MORPHTARGETS_NORMAL"] = false;
  38976. defines["MORPHTARGETS"] = false;
  38977. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38978. }
  38979. }
  38980. return true;
  38981. };
  38982. /**
  38983. * Prepares the defines related to the light information passed in parameter
  38984. * @param scene The scene we are intending to draw
  38985. * @param mesh The mesh the effect is compiling for
  38986. * @param defines The defines to update
  38987. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38988. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38989. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38990. * @returns true if normals will be required for the rest of the effect
  38991. */
  38992. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38993. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38994. if (disableLighting === void 0) { disableLighting = false; }
  38995. if (!defines._areLightsDirty) {
  38996. return defines._needNormals;
  38997. }
  38998. var lightIndex = 0;
  38999. var needNormals = false;
  39000. var needRebuild = false;
  39001. var lightmapMode = false;
  39002. var shadowEnabled = false;
  39003. var specularEnabled = false;
  39004. if (scene.lightsEnabled && !disableLighting) {
  39005. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  39006. var light = _a[_i];
  39007. needNormals = true;
  39008. if (defines["LIGHT" + lightIndex] === undefined) {
  39009. needRebuild = true;
  39010. }
  39011. defines["LIGHT" + lightIndex] = true;
  39012. defines["SPOTLIGHT" + lightIndex] = false;
  39013. defines["HEMILIGHT" + lightIndex] = false;
  39014. defines["POINTLIGHT" + lightIndex] = false;
  39015. defines["DIRLIGHT" + lightIndex] = false;
  39016. var type;
  39017. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  39018. type = "SPOTLIGHT" + lightIndex;
  39019. var spotLight = light;
  39020. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  39021. }
  39022. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  39023. type = "HEMILIGHT" + lightIndex;
  39024. }
  39025. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39026. type = "POINTLIGHT" + lightIndex;
  39027. }
  39028. else {
  39029. type = "DIRLIGHT" + lightIndex;
  39030. }
  39031. defines[type] = true;
  39032. // Specular
  39033. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39034. specularEnabled = true;
  39035. }
  39036. // Shadows
  39037. defines["SHADOW" + lightIndex] = false;
  39038. defines["SHADOWPCF" + lightIndex] = false;
  39039. defines["SHADOWPCSS" + lightIndex] = false;
  39040. defines["SHADOWPOISSON" + lightIndex] = false;
  39041. defines["SHADOWESM" + lightIndex] = false;
  39042. defines["SHADOWCUBE" + lightIndex] = false;
  39043. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39044. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39045. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39046. var shadowGenerator = light.getShadowGenerator();
  39047. if (shadowGenerator) {
  39048. shadowEnabled = true;
  39049. shadowGenerator.prepareDefines(defines, lightIndex);
  39050. }
  39051. }
  39052. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39053. lightmapMode = true;
  39054. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39055. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39056. }
  39057. else {
  39058. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39059. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39060. }
  39061. lightIndex++;
  39062. if (lightIndex === maxSimultaneousLights)
  39063. break;
  39064. }
  39065. }
  39066. defines["SPECULARTERM"] = specularEnabled;
  39067. defines["SHADOWS"] = shadowEnabled;
  39068. // Resetting all other lights if any
  39069. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39070. if (defines["LIGHT" + index] !== undefined) {
  39071. defines["LIGHT" + index] = false;
  39072. defines["HEMILIGHT" + lightIndex] = false;
  39073. defines["POINTLIGHT" + lightIndex] = false;
  39074. defines["DIRLIGHT" + lightIndex] = false;
  39075. defines["SPOTLIGHT" + lightIndex] = false;
  39076. defines["SHADOW" + lightIndex] = false;
  39077. }
  39078. }
  39079. var caps = scene.getEngine().getCaps();
  39080. if (defines["SHADOWFLOAT"] === undefined) {
  39081. needRebuild = true;
  39082. }
  39083. defines["SHADOWFLOAT"] = shadowEnabled &&
  39084. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39085. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39086. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39087. if (needRebuild) {
  39088. defines.rebuild();
  39089. }
  39090. return needNormals;
  39091. };
  39092. /**
  39093. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39094. * that won t be acctive due to defines being turned off.
  39095. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39096. * @param samplersList The samplers list
  39097. * @param defines The defines helping in the list generation
  39098. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39099. */
  39100. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39101. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39102. var uniformsList;
  39103. var uniformBuffersList = null;
  39104. if (uniformsListOrOptions.uniformsNames) {
  39105. var options = uniformsListOrOptions;
  39106. uniformsList = options.uniformsNames;
  39107. uniformBuffersList = options.uniformBuffersNames;
  39108. samplersList = options.samplers;
  39109. defines = options.defines;
  39110. maxSimultaneousLights = options.maxSimultaneousLights;
  39111. }
  39112. else {
  39113. uniformsList = uniformsListOrOptions;
  39114. if (!samplersList) {
  39115. samplersList = [];
  39116. }
  39117. }
  39118. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39119. if (!defines["LIGHT" + lightIndex]) {
  39120. break;
  39121. }
  39122. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39123. if (uniformBuffersList) {
  39124. uniformBuffersList.push("Light" + lightIndex);
  39125. }
  39126. samplersList.push("shadowSampler" + lightIndex);
  39127. samplersList.push("depthSampler" + lightIndex);
  39128. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39129. samplersList.push("projectionLightSampler" + lightIndex);
  39130. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39131. }
  39132. }
  39133. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39134. uniformsList.push("morphTargetInfluences");
  39135. }
  39136. };
  39137. /**
  39138. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39139. * @param defines The defines to update while falling back
  39140. * @param fallbacks The authorized effect fallbacks
  39141. * @param maxSimultaneousLights The maximum number of lights allowed
  39142. * @param rank the current rank of the Effect
  39143. * @returns The newly affected rank
  39144. */
  39145. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39146. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39147. if (rank === void 0) { rank = 0; }
  39148. var lightFallbackRank = 0;
  39149. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39150. if (!defines["LIGHT" + lightIndex]) {
  39151. break;
  39152. }
  39153. if (lightIndex > 0) {
  39154. lightFallbackRank = rank + lightIndex;
  39155. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39156. }
  39157. if (!defines["SHADOWS"]) {
  39158. if (defines["SHADOW" + lightIndex]) {
  39159. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39160. }
  39161. if (defines["SHADOWPCF" + lightIndex]) {
  39162. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39163. }
  39164. if (defines["SHADOWPCSS" + lightIndex]) {
  39165. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39166. }
  39167. if (defines["SHADOWPOISSON" + lightIndex]) {
  39168. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39169. }
  39170. if (defines["SHADOWESM" + lightIndex]) {
  39171. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39172. }
  39173. }
  39174. }
  39175. return lightFallbackRank++;
  39176. };
  39177. /**
  39178. * Prepares the list of attributes required for morph targets according to the effect defines.
  39179. * @param attribs The current list of supported attribs
  39180. * @param mesh The mesh to prepare the morph targets attributes for
  39181. * @param defines The current Defines of the effect
  39182. */
  39183. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39184. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39185. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39186. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39187. var manager = mesh.morphTargetManager;
  39188. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39189. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39190. for (var index = 0; index < influencers; index++) {
  39191. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39192. if (normal) {
  39193. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39194. }
  39195. if (tangent) {
  39196. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39197. }
  39198. if (attribs.length > maxAttributesCount) {
  39199. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39200. }
  39201. }
  39202. }
  39203. };
  39204. /**
  39205. * Prepares the list of attributes required for bones according to the effect defines.
  39206. * @param attribs The current list of supported attribs
  39207. * @param mesh The mesh to prepare the bones attributes for
  39208. * @param defines The current Defines of the effect
  39209. * @param fallbacks The current efffect fallback strategy
  39210. */
  39211. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39212. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39213. fallbacks.addCPUSkinningFallback(0, mesh);
  39214. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39215. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39216. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39217. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39218. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39219. }
  39220. }
  39221. };
  39222. /**
  39223. * Prepares the list of attributes required for instances according to the effect defines.
  39224. * @param attribs The current list of supported attribs
  39225. * @param defines The current Defines of the effect
  39226. */
  39227. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39228. if (defines["INSTANCES"]) {
  39229. attribs.push("world0");
  39230. attribs.push("world1");
  39231. attribs.push("world2");
  39232. attribs.push("world3");
  39233. }
  39234. };
  39235. /**
  39236. * Binds the light shadow information to the effect for the given mesh.
  39237. * @param light The light containing the generator
  39238. * @param scene The scene the lights belongs to
  39239. * @param mesh The mesh we are binding the information to render
  39240. * @param lightIndex The light index in the effect used to render the mesh
  39241. * @param effect The effect we are binding the data to
  39242. */
  39243. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39244. if (light.shadowEnabled && mesh.receiveShadows) {
  39245. var shadowGenerator = light.getShadowGenerator();
  39246. if (shadowGenerator) {
  39247. shadowGenerator.bindShadowLight(lightIndex, effect);
  39248. }
  39249. }
  39250. };
  39251. /**
  39252. * Binds the light information to the effect.
  39253. * @param light The light containing the generator
  39254. * @param effect The effect we are binding the data to
  39255. * @param lightIndex The light index in the effect used to render
  39256. */
  39257. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39258. light.transferToEffect(effect, lightIndex + "");
  39259. };
  39260. /**
  39261. * Binds the lights information from the scene to the effect for the given mesh.
  39262. * @param scene The scene the lights belongs to
  39263. * @param mesh The mesh we are binding the information to render
  39264. * @param effect The effect we are binding the data to
  39265. * @param defines The generated defines for the effect
  39266. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39267. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39268. */
  39269. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39270. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39271. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39272. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39273. for (var i = 0; i < len; i++) {
  39274. var light = mesh._lightSources[i];
  39275. var iAsString = i.toString();
  39276. var scaledIntensity = light.getScaledIntensity();
  39277. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39278. MaterialHelper.BindLightProperties(light, effect, i);
  39279. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39280. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39281. if (defines["SPECULARTERM"]) {
  39282. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39283. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39284. }
  39285. // Shadows
  39286. if (scene.shadowsEnabled) {
  39287. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39288. }
  39289. light._uniformBuffer.update();
  39290. }
  39291. };
  39292. /**
  39293. * Binds the fog information from the scene to the effect for the given mesh.
  39294. * @param scene The scene the lights belongs to
  39295. * @param mesh The mesh we are binding the information to render
  39296. * @param effect The effect we are binding the data to
  39297. */
  39298. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39299. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39300. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39301. effect.setColor3("vFogColor", scene.fogColor);
  39302. }
  39303. };
  39304. /**
  39305. * Binds the bones information from the mesh to the effect.
  39306. * @param mesh The mesh we are binding the information to render
  39307. * @param effect The effect we are binding the data to
  39308. */
  39309. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39310. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39311. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39312. if (matrices && effect) {
  39313. effect.setMatrices("mBones", matrices);
  39314. }
  39315. }
  39316. };
  39317. /**
  39318. * Binds the morph targets information from the mesh to the effect.
  39319. * @param abstractMesh The mesh we are binding the information to render
  39320. * @param effect The effect we are binding the data to
  39321. */
  39322. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39323. var manager = abstractMesh.morphTargetManager;
  39324. if (!abstractMesh || !manager) {
  39325. return;
  39326. }
  39327. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39328. };
  39329. /**
  39330. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39331. * @param defines The generated defines used in the effect
  39332. * @param effect The effect we are binding the data to
  39333. * @param scene The scene we are willing to render with logarithmic scale for
  39334. */
  39335. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39336. if (defines["LOGARITHMICDEPTH"]) {
  39337. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39338. }
  39339. };
  39340. /**
  39341. * Binds the clip plane information from the scene to the effect.
  39342. * @param scene The scene the clip plane information are extracted from
  39343. * @param effect The effect we are binding the data to
  39344. */
  39345. MaterialHelper.BindClipPlane = function (effect, scene) {
  39346. if (scene.clipPlane) {
  39347. var clipPlane = scene.clipPlane;
  39348. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39349. }
  39350. };
  39351. return MaterialHelper;
  39352. }());
  39353. BABYLON.MaterialHelper = MaterialHelper;
  39354. })(BABYLON || (BABYLON = {}));
  39355. //# sourceMappingURL=babylon.materialHelper.js.map
  39356. "use strict";
  39357. var BABYLON;
  39358. (function (BABYLON) {
  39359. var PushMaterial = /** @class */ (function (_super) {
  39360. __extends(PushMaterial, _super);
  39361. function PushMaterial(name, scene) {
  39362. var _this = _super.call(this, name, scene) || this;
  39363. _this._normalMatrix = new BABYLON.Matrix();
  39364. _this.storeEffectOnSubMeshes = true;
  39365. return _this;
  39366. }
  39367. PushMaterial.prototype.getEffect = function () {
  39368. return this._activeEffect;
  39369. };
  39370. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39371. if (!mesh) {
  39372. return false;
  39373. }
  39374. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39375. return true;
  39376. }
  39377. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39378. };
  39379. /**
  39380. * Binds the given world matrix to the active effect
  39381. *
  39382. * @param world the matrix to bind
  39383. */
  39384. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39385. this._activeEffect.setMatrix("world", world);
  39386. };
  39387. /**
  39388. * Binds the given normal matrix to the active effect
  39389. *
  39390. * @param normalMatrix the matrix to bind
  39391. */
  39392. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39393. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39394. };
  39395. PushMaterial.prototype.bind = function (world, mesh) {
  39396. if (!mesh) {
  39397. return;
  39398. }
  39399. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39400. };
  39401. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39402. if (effect === void 0) { effect = null; }
  39403. _super.prototype._afterBind.call(this, mesh);
  39404. this.getScene()._cachedEffect = effect;
  39405. };
  39406. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39407. if (visibility === void 0) { visibility = 1; }
  39408. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39409. };
  39410. return PushMaterial;
  39411. }(BABYLON.Material));
  39412. BABYLON.PushMaterial = PushMaterial;
  39413. })(BABYLON || (BABYLON = {}));
  39414. //# sourceMappingURL=babylon.pushMaterial.js.map
  39415. "use strict";
  39416. var BABYLON;
  39417. (function (BABYLON) {
  39418. /** @ignore */
  39419. var StandardMaterialDefines = /** @class */ (function (_super) {
  39420. __extends(StandardMaterialDefines, _super);
  39421. function StandardMaterialDefines() {
  39422. var _this = _super.call(this) || this;
  39423. _this.MAINUV1 = false;
  39424. _this.MAINUV2 = false;
  39425. _this.DIFFUSE = false;
  39426. _this.DIFFUSEDIRECTUV = 0;
  39427. _this.AMBIENT = false;
  39428. _this.AMBIENTDIRECTUV = 0;
  39429. _this.OPACITY = false;
  39430. _this.OPACITYDIRECTUV = 0;
  39431. _this.OPACITYRGB = false;
  39432. _this.REFLECTION = false;
  39433. _this.EMISSIVE = false;
  39434. _this.EMISSIVEDIRECTUV = 0;
  39435. _this.SPECULAR = false;
  39436. _this.SPECULARDIRECTUV = 0;
  39437. _this.BUMP = false;
  39438. _this.BUMPDIRECTUV = 0;
  39439. _this.PARALLAX = false;
  39440. _this.PARALLAXOCCLUSION = false;
  39441. _this.SPECULAROVERALPHA = false;
  39442. _this.CLIPPLANE = false;
  39443. _this.ALPHATEST = false;
  39444. _this.DEPTHPREPASS = false;
  39445. _this.ALPHAFROMDIFFUSE = false;
  39446. _this.POINTSIZE = false;
  39447. _this.FOG = false;
  39448. _this.SPECULARTERM = false;
  39449. _this.DIFFUSEFRESNEL = false;
  39450. _this.OPACITYFRESNEL = false;
  39451. _this.REFLECTIONFRESNEL = false;
  39452. _this.REFRACTIONFRESNEL = false;
  39453. _this.EMISSIVEFRESNEL = false;
  39454. _this.FRESNEL = false;
  39455. _this.NORMAL = false;
  39456. _this.UV1 = false;
  39457. _this.UV2 = false;
  39458. _this.VERTEXCOLOR = false;
  39459. _this.VERTEXALPHA = false;
  39460. _this.NUM_BONE_INFLUENCERS = 0;
  39461. _this.BonesPerMesh = 0;
  39462. _this.INSTANCES = false;
  39463. _this.GLOSSINESS = false;
  39464. _this.ROUGHNESS = false;
  39465. _this.EMISSIVEASILLUMINATION = false;
  39466. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39467. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39468. _this.LIGHTMAP = false;
  39469. _this.LIGHTMAPDIRECTUV = 0;
  39470. _this.OBJECTSPACE_NORMALMAP = false;
  39471. _this.USELIGHTMAPASSHADOWMAP = false;
  39472. _this.REFLECTIONMAP_3D = false;
  39473. _this.REFLECTIONMAP_SPHERICAL = false;
  39474. _this.REFLECTIONMAP_PLANAR = false;
  39475. _this.REFLECTIONMAP_CUBIC = false;
  39476. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39477. _this.REFLECTIONMAP_PROJECTION = false;
  39478. _this.REFLECTIONMAP_SKYBOX = false;
  39479. _this.REFLECTIONMAP_EXPLICIT = false;
  39480. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39481. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39482. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39483. _this.INVERTCUBICMAP = false;
  39484. _this.LOGARITHMICDEPTH = false;
  39485. _this.REFRACTION = false;
  39486. _this.REFRACTIONMAP_3D = false;
  39487. _this.REFLECTIONOVERALPHA = false;
  39488. _this.TWOSIDEDLIGHTING = false;
  39489. _this.SHADOWFLOAT = false;
  39490. _this.MORPHTARGETS = false;
  39491. _this.MORPHTARGETS_NORMAL = false;
  39492. _this.MORPHTARGETS_TANGENT = false;
  39493. _this.NUM_MORPH_INFLUENCERS = 0;
  39494. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39495. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39496. _this.IMAGEPROCESSING = false;
  39497. _this.VIGNETTE = false;
  39498. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39499. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39500. _this.TONEMAPPING = false;
  39501. _this.CONTRAST = false;
  39502. _this.COLORCURVES = false;
  39503. _this.COLORGRADING = false;
  39504. _this.COLORGRADING3D = false;
  39505. _this.SAMPLER3DGREENDEPTH = false;
  39506. _this.SAMPLER3DBGRMAP = false;
  39507. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39508. _this.EXPOSURE = false;
  39509. _this.GRAIN = false;
  39510. _this.rebuild();
  39511. return _this;
  39512. }
  39513. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39514. var modes = [
  39515. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39516. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39517. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39518. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39519. ];
  39520. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39521. var mode = modes_1[_i];
  39522. this[mode] = (mode === modeToEnable);
  39523. }
  39524. };
  39525. return StandardMaterialDefines;
  39526. }(BABYLON.MaterialDefines));
  39527. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39528. var StandardMaterial = /** @class */ (function (_super) {
  39529. __extends(StandardMaterial, _super);
  39530. function StandardMaterial(name, scene) {
  39531. var _this = _super.call(this, name, scene) || this;
  39532. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39533. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39534. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39535. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39536. _this.specularPower = 64;
  39537. _this._useAlphaFromDiffuseTexture = false;
  39538. _this._useEmissiveAsIllumination = false;
  39539. _this._linkEmissiveWithDiffuse = false;
  39540. _this._useSpecularOverAlpha = false;
  39541. _this._useReflectionOverAlpha = false;
  39542. _this._disableLighting = false;
  39543. _this._useObjectSpaceNormalMap = false;
  39544. _this._useParallax = false;
  39545. _this._useParallaxOcclusion = false;
  39546. _this.parallaxScaleBias = 0.05;
  39547. _this._roughness = 0;
  39548. _this.indexOfRefraction = 0.98;
  39549. _this.invertRefractionY = true;
  39550. _this._useLightmapAsShadowmap = false;
  39551. _this._useReflectionFresnelFromSpecular = false;
  39552. _this._useGlossinessFromSpecularMapAlpha = false;
  39553. _this._maxSimultaneousLights = 4;
  39554. /**
  39555. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39556. */
  39557. _this._invertNormalMapX = false;
  39558. /**
  39559. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39560. */
  39561. _this._invertNormalMapY = false;
  39562. /**
  39563. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39564. */
  39565. _this._twoSidedLighting = false;
  39566. _this._renderTargets = new BABYLON.SmartArray(16);
  39567. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39568. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39569. // Setup the default processing configuration to the scene.
  39570. _this._attachImageProcessingConfiguration(null);
  39571. _this.getRenderTargetTextures = function () {
  39572. _this._renderTargets.reset();
  39573. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39574. _this._renderTargets.push(_this._reflectionTexture);
  39575. }
  39576. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39577. _this._renderTargets.push(_this._refractionTexture);
  39578. }
  39579. return _this._renderTargets;
  39580. };
  39581. return _this;
  39582. }
  39583. ;
  39584. ;
  39585. ;
  39586. ;
  39587. ;
  39588. ;
  39589. ;
  39590. ;
  39591. ;
  39592. ;
  39593. ;
  39594. ;
  39595. ;
  39596. ;
  39597. ;
  39598. ;
  39599. ;
  39600. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39601. /**
  39602. * Gets the image processing configuration used either in this material.
  39603. */
  39604. get: function () {
  39605. return this._imageProcessingConfiguration;
  39606. },
  39607. /**
  39608. * Sets the Default image processing configuration used either in the this material.
  39609. *
  39610. * If sets to null, the scene one is in use.
  39611. */
  39612. set: function (value) {
  39613. this._attachImageProcessingConfiguration(value);
  39614. // Ensure the effect will be rebuilt.
  39615. this._markAllSubMeshesAsTexturesDirty();
  39616. },
  39617. enumerable: true,
  39618. configurable: true
  39619. });
  39620. /**
  39621. * Attaches a new image processing configuration to the Standard Material.
  39622. * @param configuration
  39623. */
  39624. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39625. var _this = this;
  39626. if (configuration === this._imageProcessingConfiguration) {
  39627. return;
  39628. }
  39629. // Detaches observer.
  39630. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39631. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39632. }
  39633. // Pick the scene configuration if needed.
  39634. if (!configuration) {
  39635. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39636. }
  39637. else {
  39638. this._imageProcessingConfiguration = configuration;
  39639. }
  39640. // Attaches observer.
  39641. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39642. _this._markAllSubMeshesAsImageProcessingDirty();
  39643. });
  39644. };
  39645. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39646. /**
  39647. * Gets wether the color curves effect is enabled.
  39648. */
  39649. get: function () {
  39650. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39651. },
  39652. /**
  39653. * Sets wether the color curves effect is enabled.
  39654. */
  39655. set: function (value) {
  39656. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39657. },
  39658. enumerable: true,
  39659. configurable: true
  39660. });
  39661. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39662. /**
  39663. * Gets wether the color grading effect is enabled.
  39664. */
  39665. get: function () {
  39666. return this.imageProcessingConfiguration.colorGradingEnabled;
  39667. },
  39668. /**
  39669. * Gets wether the color grading effect is enabled.
  39670. */
  39671. set: function (value) {
  39672. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39673. },
  39674. enumerable: true,
  39675. configurable: true
  39676. });
  39677. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39678. /**
  39679. * Gets wether tonemapping is enabled or not.
  39680. */
  39681. get: function () {
  39682. return this._imageProcessingConfiguration.toneMappingEnabled;
  39683. },
  39684. /**
  39685. * Sets wether tonemapping is enabled or not
  39686. */
  39687. set: function (value) {
  39688. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39689. },
  39690. enumerable: true,
  39691. configurable: true
  39692. });
  39693. ;
  39694. ;
  39695. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39696. /**
  39697. * The camera exposure used on this material.
  39698. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39699. * This corresponds to a photographic exposure.
  39700. */
  39701. get: function () {
  39702. return this._imageProcessingConfiguration.exposure;
  39703. },
  39704. /**
  39705. * The camera exposure used on this material.
  39706. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39707. * This corresponds to a photographic exposure.
  39708. */
  39709. set: function (value) {
  39710. this._imageProcessingConfiguration.exposure = value;
  39711. },
  39712. enumerable: true,
  39713. configurable: true
  39714. });
  39715. ;
  39716. ;
  39717. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39718. /**
  39719. * Gets The camera contrast used on this material.
  39720. */
  39721. get: function () {
  39722. return this._imageProcessingConfiguration.contrast;
  39723. },
  39724. /**
  39725. * Sets The camera contrast used on this material.
  39726. */
  39727. set: function (value) {
  39728. this._imageProcessingConfiguration.contrast = value;
  39729. },
  39730. enumerable: true,
  39731. configurable: true
  39732. });
  39733. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39734. /**
  39735. * Gets the Color Grading 2D Lookup Texture.
  39736. */
  39737. get: function () {
  39738. return this._imageProcessingConfiguration.colorGradingTexture;
  39739. },
  39740. /**
  39741. * Sets the Color Grading 2D Lookup Texture.
  39742. */
  39743. set: function (value) {
  39744. this._imageProcessingConfiguration.colorGradingTexture = value;
  39745. },
  39746. enumerable: true,
  39747. configurable: true
  39748. });
  39749. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39750. /**
  39751. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39752. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39753. * 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;
  39754. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39755. */
  39756. get: function () {
  39757. return this._imageProcessingConfiguration.colorCurves;
  39758. },
  39759. /**
  39760. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39761. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39762. * 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;
  39763. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39764. */
  39765. set: function (value) {
  39766. this._imageProcessingConfiguration.colorCurves = value;
  39767. },
  39768. enumerable: true,
  39769. configurable: true
  39770. });
  39771. StandardMaterial.prototype.getClassName = function () {
  39772. return "StandardMaterial";
  39773. };
  39774. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39775. get: function () {
  39776. return this._useLogarithmicDepth;
  39777. },
  39778. set: function (value) {
  39779. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39780. this._markAllSubMeshesAsMiscDirty();
  39781. },
  39782. enumerable: true,
  39783. configurable: true
  39784. });
  39785. StandardMaterial.prototype.needAlphaBlending = function () {
  39786. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39787. };
  39788. StandardMaterial.prototype.needAlphaTesting = function () {
  39789. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39790. };
  39791. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39792. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39793. };
  39794. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39795. return this._diffuseTexture;
  39796. };
  39797. /**
  39798. * Child classes can use it to update shaders
  39799. */
  39800. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39801. if (useInstances === void 0) { useInstances = false; }
  39802. if (subMesh.effect && this.isFrozen) {
  39803. if (this._wasPreviouslyReady && subMesh.effect) {
  39804. return true;
  39805. }
  39806. }
  39807. if (!subMesh._materialDefines) {
  39808. subMesh._materialDefines = new StandardMaterialDefines();
  39809. }
  39810. var scene = this.getScene();
  39811. var defines = subMesh._materialDefines;
  39812. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39813. if (defines._renderId === scene.getRenderId()) {
  39814. return true;
  39815. }
  39816. }
  39817. var engine = scene.getEngine();
  39818. // Lights
  39819. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39820. // Textures
  39821. if (defines._areTexturesDirty) {
  39822. defines._needUVs = false;
  39823. defines.MAINUV1 = false;
  39824. defines.MAINUV2 = false;
  39825. if (scene.texturesEnabled) {
  39826. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39827. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39828. return false;
  39829. }
  39830. else {
  39831. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39832. }
  39833. }
  39834. else {
  39835. defines.DIFFUSE = false;
  39836. }
  39837. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39838. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39839. return false;
  39840. }
  39841. else {
  39842. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39843. }
  39844. }
  39845. else {
  39846. defines.AMBIENT = false;
  39847. }
  39848. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39849. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39850. return false;
  39851. }
  39852. else {
  39853. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39854. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39855. }
  39856. }
  39857. else {
  39858. defines.OPACITY = false;
  39859. }
  39860. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39861. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39862. return false;
  39863. }
  39864. else {
  39865. defines._needNormals = true;
  39866. defines.REFLECTION = true;
  39867. defines.ROUGHNESS = (this._roughness > 0);
  39868. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39869. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39870. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39871. switch (this._reflectionTexture.coordinatesMode) {
  39872. case BABYLON.Texture.CUBIC_MODE:
  39873. case BABYLON.Texture.INVCUBIC_MODE:
  39874. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39875. break;
  39876. case BABYLON.Texture.EXPLICIT_MODE:
  39877. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39878. break;
  39879. case BABYLON.Texture.PLANAR_MODE:
  39880. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39881. break;
  39882. case BABYLON.Texture.PROJECTION_MODE:
  39883. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39884. break;
  39885. case BABYLON.Texture.SKYBOX_MODE:
  39886. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39887. break;
  39888. case BABYLON.Texture.SPHERICAL_MODE:
  39889. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39890. break;
  39891. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39892. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39893. break;
  39894. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39895. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39896. break;
  39897. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39898. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39899. break;
  39900. }
  39901. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39902. }
  39903. }
  39904. else {
  39905. defines.REFLECTION = false;
  39906. }
  39907. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39908. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39909. return false;
  39910. }
  39911. else {
  39912. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39913. }
  39914. }
  39915. else {
  39916. defines.EMISSIVE = false;
  39917. }
  39918. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39919. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39920. return false;
  39921. }
  39922. else {
  39923. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39924. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39925. }
  39926. }
  39927. else {
  39928. defines.LIGHTMAP = false;
  39929. }
  39930. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39931. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39932. return false;
  39933. }
  39934. else {
  39935. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39936. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39937. }
  39938. }
  39939. else {
  39940. defines.SPECULAR = false;
  39941. }
  39942. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39943. // Bump texure can not be not blocking.
  39944. if (!this._bumpTexture.isReady()) {
  39945. return false;
  39946. }
  39947. else {
  39948. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39949. defines.PARALLAX = this._useParallax;
  39950. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39951. }
  39952. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39953. }
  39954. else {
  39955. defines.BUMP = false;
  39956. }
  39957. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39958. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39959. return false;
  39960. }
  39961. else {
  39962. defines._needUVs = true;
  39963. defines.REFRACTION = true;
  39964. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39965. }
  39966. }
  39967. else {
  39968. defines.REFRACTION = false;
  39969. }
  39970. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39971. }
  39972. else {
  39973. defines.DIFFUSE = false;
  39974. defines.AMBIENT = false;
  39975. defines.OPACITY = false;
  39976. defines.REFLECTION = false;
  39977. defines.EMISSIVE = false;
  39978. defines.LIGHTMAP = false;
  39979. defines.BUMP = false;
  39980. defines.REFRACTION = false;
  39981. }
  39982. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39983. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39984. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39985. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39986. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39987. }
  39988. if (defines._areImageProcessingDirty) {
  39989. if (!this._imageProcessingConfiguration.isReady()) {
  39990. return false;
  39991. }
  39992. this._imageProcessingConfiguration.prepareDefines(defines);
  39993. }
  39994. if (defines._areFresnelDirty) {
  39995. if (StandardMaterial.FresnelEnabled) {
  39996. // Fresnel
  39997. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39998. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39999. this._reflectionFresnelParameters) {
  40000. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  40001. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  40002. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  40003. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  40004. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  40005. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  40006. defines._needNormals = true;
  40007. defines.FRESNEL = true;
  40008. }
  40009. }
  40010. else {
  40011. defines.FRESNEL = false;
  40012. }
  40013. }
  40014. // Misc.
  40015. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  40016. // Attribs
  40017. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40018. // Values that need to be evaluated on every frame
  40019. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40020. // Get correct effect
  40021. if (defines.isDirty) {
  40022. defines.markAsProcessed();
  40023. scene.resetCachedMaterial();
  40024. // Fallbacks
  40025. var fallbacks = new BABYLON.EffectFallbacks();
  40026. if (defines.REFLECTION) {
  40027. fallbacks.addFallback(0, "REFLECTION");
  40028. }
  40029. if (defines.SPECULAR) {
  40030. fallbacks.addFallback(0, "SPECULAR");
  40031. }
  40032. if (defines.BUMP) {
  40033. fallbacks.addFallback(0, "BUMP");
  40034. }
  40035. if (defines.PARALLAX) {
  40036. fallbacks.addFallback(1, "PARALLAX");
  40037. }
  40038. if (defines.PARALLAXOCCLUSION) {
  40039. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40040. }
  40041. if (defines.SPECULAROVERALPHA) {
  40042. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40043. }
  40044. if (defines.FOG) {
  40045. fallbacks.addFallback(1, "FOG");
  40046. }
  40047. if (defines.POINTSIZE) {
  40048. fallbacks.addFallback(0, "POINTSIZE");
  40049. }
  40050. if (defines.LOGARITHMICDEPTH) {
  40051. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40052. }
  40053. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40054. if (defines.SPECULARTERM) {
  40055. fallbacks.addFallback(0, "SPECULARTERM");
  40056. }
  40057. if (defines.DIFFUSEFRESNEL) {
  40058. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40059. }
  40060. if (defines.OPACITYFRESNEL) {
  40061. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40062. }
  40063. if (defines.REFLECTIONFRESNEL) {
  40064. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40065. }
  40066. if (defines.EMISSIVEFRESNEL) {
  40067. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40068. }
  40069. if (defines.FRESNEL) {
  40070. fallbacks.addFallback(4, "FRESNEL");
  40071. }
  40072. //Attributes
  40073. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40074. if (defines.NORMAL) {
  40075. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40076. }
  40077. if (defines.UV1) {
  40078. attribs.push(BABYLON.VertexBuffer.UVKind);
  40079. }
  40080. if (defines.UV2) {
  40081. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40082. }
  40083. if (defines.VERTEXCOLOR) {
  40084. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40085. }
  40086. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40087. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40088. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40089. var shaderName = "default";
  40090. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40091. "vFogInfos", "vFogColor", "pointSize",
  40092. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40093. "mBones",
  40094. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40095. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40096. "vReflectionPosition", "vReflectionSize",
  40097. "logarithmicDepthConstant", "vTangentSpaceParams"
  40098. ];
  40099. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40100. var uniformBuffers = ["Material", "Scene"];
  40101. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40102. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40103. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40104. uniformsNames: uniforms,
  40105. uniformBuffersNames: uniformBuffers,
  40106. samplers: samplers,
  40107. defines: defines,
  40108. maxSimultaneousLights: this._maxSimultaneousLights
  40109. });
  40110. if (this.customShaderNameResolve) {
  40111. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40112. }
  40113. var join = defines.toString();
  40114. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40115. attributes: attribs,
  40116. uniformsNames: uniforms,
  40117. uniformBuffersNames: uniformBuffers,
  40118. samplers: samplers,
  40119. defines: join,
  40120. fallbacks: fallbacks,
  40121. onCompiled: this.onCompiled,
  40122. onError: this.onError,
  40123. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40124. }, engine), defines);
  40125. this.buildUniformLayout();
  40126. }
  40127. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40128. return false;
  40129. }
  40130. defines._renderId = scene.getRenderId();
  40131. this._wasPreviouslyReady = true;
  40132. return true;
  40133. };
  40134. StandardMaterial.prototype.buildUniformLayout = function () {
  40135. // Order is important !
  40136. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40137. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40138. this._uniformBuffer.addUniform("opacityParts", 4);
  40139. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40140. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40141. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40142. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40143. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40144. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40145. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40146. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40147. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40148. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40149. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40150. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40151. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40152. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40153. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40154. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40155. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40156. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40157. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40158. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40159. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40160. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40161. this._uniformBuffer.addUniform("specularMatrix", 16);
  40162. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40163. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40164. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40165. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40166. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40167. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40168. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40169. this._uniformBuffer.addUniform("pointSize", 1);
  40170. this._uniformBuffer.create();
  40171. };
  40172. StandardMaterial.prototype.unbind = function () {
  40173. if (this._activeEffect) {
  40174. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40175. this._activeEffect.setTexture("reflection2DSampler", null);
  40176. }
  40177. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40178. this._activeEffect.setTexture("refraction2DSampler", null);
  40179. }
  40180. }
  40181. _super.prototype.unbind.call(this);
  40182. };
  40183. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40184. var scene = this.getScene();
  40185. var defines = subMesh._materialDefines;
  40186. if (!defines) {
  40187. return;
  40188. }
  40189. var effect = subMesh.effect;
  40190. if (!effect) {
  40191. return;
  40192. }
  40193. this._activeEffect = effect;
  40194. // Matrices
  40195. this.bindOnlyWorldMatrix(world);
  40196. // Normal Matrix
  40197. if (defines.OBJECTSPACE_NORMALMAP) {
  40198. world.toNormalMatrix(this._normalMatrix);
  40199. this.bindOnlyNormalMatrix(this._normalMatrix);
  40200. }
  40201. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40202. // Bones
  40203. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40204. if (mustRebind) {
  40205. this._uniformBuffer.bindToEffect(effect, "Material");
  40206. this.bindViewProjection(effect);
  40207. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40208. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40209. // Fresnel
  40210. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40211. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40212. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40213. }
  40214. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40215. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40216. }
  40217. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40218. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40219. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40220. }
  40221. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40222. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40223. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40224. }
  40225. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40226. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40227. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40228. }
  40229. }
  40230. // Textures
  40231. if (scene.texturesEnabled) {
  40232. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40233. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40234. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40235. }
  40236. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40237. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40238. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40239. }
  40240. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40241. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40242. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40243. }
  40244. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40245. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40246. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40247. if (this._reflectionTexture.boundingBoxSize) {
  40248. var cubeTexture = this._reflectionTexture;
  40249. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40250. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40251. }
  40252. }
  40253. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40254. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40255. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40256. }
  40257. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40258. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40259. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40260. }
  40261. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40262. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40263. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40264. }
  40265. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40266. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40267. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40268. if (scene._mirroredCameraPosition) {
  40269. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40270. }
  40271. else {
  40272. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40273. }
  40274. }
  40275. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40276. var depth = 1.0;
  40277. if (!this._refractionTexture.isCube) {
  40278. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40279. if (this._refractionTexture.depth) {
  40280. depth = this._refractionTexture.depth;
  40281. }
  40282. }
  40283. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40284. }
  40285. }
  40286. // Point size
  40287. if (this.pointsCloud) {
  40288. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40289. }
  40290. if (defines.SPECULARTERM) {
  40291. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40292. }
  40293. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40294. // Diffuse
  40295. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40296. }
  40297. // Textures
  40298. if (scene.texturesEnabled) {
  40299. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40300. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40301. }
  40302. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40303. effect.setTexture("ambientSampler", this._ambientTexture);
  40304. }
  40305. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40306. effect.setTexture("opacitySampler", this._opacityTexture);
  40307. }
  40308. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40309. if (this._reflectionTexture.isCube) {
  40310. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40311. }
  40312. else {
  40313. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40314. }
  40315. }
  40316. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40317. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40318. }
  40319. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40320. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40321. }
  40322. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40323. effect.setTexture("specularSampler", this._specularTexture);
  40324. }
  40325. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40326. effect.setTexture("bumpSampler", this._bumpTexture);
  40327. }
  40328. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40329. var depth = 1.0;
  40330. if (this._refractionTexture.isCube) {
  40331. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40332. }
  40333. else {
  40334. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40335. }
  40336. }
  40337. }
  40338. // Clip plane
  40339. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40340. // Colors
  40341. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40342. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40343. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40344. }
  40345. if (mustRebind || !this.isFrozen) {
  40346. // Lights
  40347. if (scene.lightsEnabled && !this._disableLighting) {
  40348. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40349. }
  40350. // View
  40351. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40352. this.bindView(effect);
  40353. }
  40354. // Fog
  40355. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40356. // Morph targets
  40357. if (defines.NUM_MORPH_INFLUENCERS) {
  40358. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40359. }
  40360. // Log. depth
  40361. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40362. // image processing
  40363. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40364. this._imageProcessingConfiguration.bind(this._activeEffect);
  40365. }
  40366. }
  40367. this._uniformBuffer.update();
  40368. this._afterBind(mesh, this._activeEffect);
  40369. };
  40370. StandardMaterial.prototype.getAnimatables = function () {
  40371. var results = [];
  40372. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40373. results.push(this._diffuseTexture);
  40374. }
  40375. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40376. results.push(this._ambientTexture);
  40377. }
  40378. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40379. results.push(this._opacityTexture);
  40380. }
  40381. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40382. results.push(this._reflectionTexture);
  40383. }
  40384. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40385. results.push(this._emissiveTexture);
  40386. }
  40387. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40388. results.push(this._specularTexture);
  40389. }
  40390. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40391. results.push(this._bumpTexture);
  40392. }
  40393. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40394. results.push(this._lightmapTexture);
  40395. }
  40396. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40397. results.push(this._refractionTexture);
  40398. }
  40399. return results;
  40400. };
  40401. StandardMaterial.prototype.getActiveTextures = function () {
  40402. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40403. if (this._diffuseTexture) {
  40404. activeTextures.push(this._diffuseTexture);
  40405. }
  40406. if (this._ambientTexture) {
  40407. activeTextures.push(this._ambientTexture);
  40408. }
  40409. if (this._opacityTexture) {
  40410. activeTextures.push(this._opacityTexture);
  40411. }
  40412. if (this._reflectionTexture) {
  40413. activeTextures.push(this._reflectionTexture);
  40414. }
  40415. if (this._emissiveTexture) {
  40416. activeTextures.push(this._emissiveTexture);
  40417. }
  40418. if (this._specularTexture) {
  40419. activeTextures.push(this._specularTexture);
  40420. }
  40421. if (this._bumpTexture) {
  40422. activeTextures.push(this._bumpTexture);
  40423. }
  40424. if (this._lightmapTexture) {
  40425. activeTextures.push(this._lightmapTexture);
  40426. }
  40427. if (this._refractionTexture) {
  40428. activeTextures.push(this._refractionTexture);
  40429. }
  40430. return activeTextures;
  40431. };
  40432. StandardMaterial.prototype.hasTexture = function (texture) {
  40433. if (_super.prototype.hasTexture.call(this, texture)) {
  40434. return true;
  40435. }
  40436. if (this._diffuseTexture === texture) {
  40437. return true;
  40438. }
  40439. if (this._ambientTexture === texture) {
  40440. return true;
  40441. }
  40442. if (this._opacityTexture === texture) {
  40443. return true;
  40444. }
  40445. if (this._reflectionTexture === texture) {
  40446. return true;
  40447. }
  40448. if (this._emissiveTexture === texture) {
  40449. return true;
  40450. }
  40451. if (this._specularTexture === texture) {
  40452. return true;
  40453. }
  40454. if (this._bumpTexture === texture) {
  40455. return true;
  40456. }
  40457. if (this._lightmapTexture === texture) {
  40458. return true;
  40459. }
  40460. if (this._refractionTexture === texture) {
  40461. return true;
  40462. }
  40463. return false;
  40464. };
  40465. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40466. if (forceDisposeTextures) {
  40467. if (this._diffuseTexture) {
  40468. this._diffuseTexture.dispose();
  40469. }
  40470. if (this._ambientTexture) {
  40471. this._ambientTexture.dispose();
  40472. }
  40473. if (this._opacityTexture) {
  40474. this._opacityTexture.dispose();
  40475. }
  40476. if (this._reflectionTexture) {
  40477. this._reflectionTexture.dispose();
  40478. }
  40479. if (this._emissiveTexture) {
  40480. this._emissiveTexture.dispose();
  40481. }
  40482. if (this._specularTexture) {
  40483. this._specularTexture.dispose();
  40484. }
  40485. if (this._bumpTexture) {
  40486. this._bumpTexture.dispose();
  40487. }
  40488. if (this._lightmapTexture) {
  40489. this._lightmapTexture.dispose();
  40490. }
  40491. if (this._refractionTexture) {
  40492. this._refractionTexture.dispose();
  40493. }
  40494. }
  40495. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40496. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40497. }
  40498. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40499. };
  40500. StandardMaterial.prototype.clone = function (name) {
  40501. var _this = this;
  40502. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40503. result.name = name;
  40504. result.id = name;
  40505. return result;
  40506. };
  40507. StandardMaterial.prototype.serialize = function () {
  40508. return BABYLON.SerializationHelper.Serialize(this);
  40509. };
  40510. // Statics
  40511. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40512. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40513. };
  40514. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40515. get: function () {
  40516. return StandardMaterial._DiffuseTextureEnabled;
  40517. },
  40518. set: function (value) {
  40519. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40520. return;
  40521. }
  40522. StandardMaterial._DiffuseTextureEnabled = value;
  40523. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40524. },
  40525. enumerable: true,
  40526. configurable: true
  40527. });
  40528. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40529. get: function () {
  40530. return StandardMaterial._AmbientTextureEnabled;
  40531. },
  40532. set: function (value) {
  40533. if (StandardMaterial._AmbientTextureEnabled === value) {
  40534. return;
  40535. }
  40536. StandardMaterial._AmbientTextureEnabled = value;
  40537. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40538. },
  40539. enumerable: true,
  40540. configurable: true
  40541. });
  40542. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40543. get: function () {
  40544. return StandardMaterial._OpacityTextureEnabled;
  40545. },
  40546. set: function (value) {
  40547. if (StandardMaterial._OpacityTextureEnabled === value) {
  40548. return;
  40549. }
  40550. StandardMaterial._OpacityTextureEnabled = value;
  40551. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40552. },
  40553. enumerable: true,
  40554. configurable: true
  40555. });
  40556. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40557. get: function () {
  40558. return StandardMaterial._ReflectionTextureEnabled;
  40559. },
  40560. set: function (value) {
  40561. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40562. return;
  40563. }
  40564. StandardMaterial._ReflectionTextureEnabled = value;
  40565. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40566. },
  40567. enumerable: true,
  40568. configurable: true
  40569. });
  40570. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40571. get: function () {
  40572. return StandardMaterial._EmissiveTextureEnabled;
  40573. },
  40574. set: function (value) {
  40575. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40576. return;
  40577. }
  40578. StandardMaterial._EmissiveTextureEnabled = value;
  40579. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40580. },
  40581. enumerable: true,
  40582. configurable: true
  40583. });
  40584. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40585. get: function () {
  40586. return StandardMaterial._SpecularTextureEnabled;
  40587. },
  40588. set: function (value) {
  40589. if (StandardMaterial._SpecularTextureEnabled === value) {
  40590. return;
  40591. }
  40592. StandardMaterial._SpecularTextureEnabled = value;
  40593. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40594. },
  40595. enumerable: true,
  40596. configurable: true
  40597. });
  40598. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40599. get: function () {
  40600. return StandardMaterial._BumpTextureEnabled;
  40601. },
  40602. set: function (value) {
  40603. if (StandardMaterial._BumpTextureEnabled === value) {
  40604. return;
  40605. }
  40606. StandardMaterial._BumpTextureEnabled = value;
  40607. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40608. },
  40609. enumerable: true,
  40610. configurable: true
  40611. });
  40612. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40613. get: function () {
  40614. return StandardMaterial._LightmapTextureEnabled;
  40615. },
  40616. set: function (value) {
  40617. if (StandardMaterial._LightmapTextureEnabled === value) {
  40618. return;
  40619. }
  40620. StandardMaterial._LightmapTextureEnabled = value;
  40621. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40622. },
  40623. enumerable: true,
  40624. configurable: true
  40625. });
  40626. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40627. get: function () {
  40628. return StandardMaterial._RefractionTextureEnabled;
  40629. },
  40630. set: function (value) {
  40631. if (StandardMaterial._RefractionTextureEnabled === value) {
  40632. return;
  40633. }
  40634. StandardMaterial._RefractionTextureEnabled = value;
  40635. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40636. },
  40637. enumerable: true,
  40638. configurable: true
  40639. });
  40640. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40641. get: function () {
  40642. return StandardMaterial._ColorGradingTextureEnabled;
  40643. },
  40644. set: function (value) {
  40645. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40646. return;
  40647. }
  40648. StandardMaterial._ColorGradingTextureEnabled = value;
  40649. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40650. },
  40651. enumerable: true,
  40652. configurable: true
  40653. });
  40654. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40655. get: function () {
  40656. return StandardMaterial._FresnelEnabled;
  40657. },
  40658. set: function (value) {
  40659. if (StandardMaterial._FresnelEnabled === value) {
  40660. return;
  40661. }
  40662. StandardMaterial._FresnelEnabled = value;
  40663. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40664. },
  40665. enumerable: true,
  40666. configurable: true
  40667. });
  40668. // Flags used to enable or disable a type of texture for all Standard Materials
  40669. StandardMaterial._DiffuseTextureEnabled = true;
  40670. StandardMaterial._AmbientTextureEnabled = true;
  40671. StandardMaterial._OpacityTextureEnabled = true;
  40672. StandardMaterial._ReflectionTextureEnabled = true;
  40673. StandardMaterial._EmissiveTextureEnabled = true;
  40674. StandardMaterial._SpecularTextureEnabled = true;
  40675. StandardMaterial._BumpTextureEnabled = true;
  40676. StandardMaterial._LightmapTextureEnabled = true;
  40677. StandardMaterial._RefractionTextureEnabled = true;
  40678. StandardMaterial._ColorGradingTextureEnabled = true;
  40679. StandardMaterial._FresnelEnabled = true;
  40680. __decorate([
  40681. BABYLON.serializeAsTexture("diffuseTexture")
  40682. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40683. __decorate([
  40684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40685. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40686. __decorate([
  40687. BABYLON.serializeAsTexture("ambientTexture")
  40688. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40689. __decorate([
  40690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40691. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40692. __decorate([
  40693. BABYLON.serializeAsTexture("opacityTexture")
  40694. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40695. __decorate([
  40696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40697. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40698. __decorate([
  40699. BABYLON.serializeAsTexture("reflectionTexture")
  40700. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40701. __decorate([
  40702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40703. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40704. __decorate([
  40705. BABYLON.serializeAsTexture("emissiveTexture")
  40706. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40707. __decorate([
  40708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40709. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40710. __decorate([
  40711. BABYLON.serializeAsTexture("specularTexture")
  40712. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40713. __decorate([
  40714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40715. ], StandardMaterial.prototype, "specularTexture", void 0);
  40716. __decorate([
  40717. BABYLON.serializeAsTexture("bumpTexture")
  40718. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40719. __decorate([
  40720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40721. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40722. __decorate([
  40723. BABYLON.serializeAsTexture("lightmapTexture")
  40724. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40725. __decorate([
  40726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40727. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40728. __decorate([
  40729. BABYLON.serializeAsTexture("refractionTexture")
  40730. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40731. __decorate([
  40732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40733. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40734. __decorate([
  40735. BABYLON.serializeAsColor3("ambient")
  40736. ], StandardMaterial.prototype, "ambientColor", void 0);
  40737. __decorate([
  40738. BABYLON.serializeAsColor3("diffuse")
  40739. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40740. __decorate([
  40741. BABYLON.serializeAsColor3("specular")
  40742. ], StandardMaterial.prototype, "specularColor", void 0);
  40743. __decorate([
  40744. BABYLON.serializeAsColor3("emissive")
  40745. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40746. __decorate([
  40747. BABYLON.serialize()
  40748. ], StandardMaterial.prototype, "specularPower", void 0);
  40749. __decorate([
  40750. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40751. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40752. __decorate([
  40753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40754. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40755. __decorate([
  40756. BABYLON.serialize("useEmissiveAsIllumination")
  40757. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40758. __decorate([
  40759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40760. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40761. __decorate([
  40762. BABYLON.serialize("linkEmissiveWithDiffuse")
  40763. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40764. __decorate([
  40765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40766. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40767. __decorate([
  40768. BABYLON.serialize("useSpecularOverAlpha")
  40769. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40770. __decorate([
  40771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40772. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40773. __decorate([
  40774. BABYLON.serialize("useReflectionOverAlpha")
  40775. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40776. __decorate([
  40777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40778. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40779. __decorate([
  40780. BABYLON.serialize("disableLighting")
  40781. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40782. __decorate([
  40783. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40784. ], StandardMaterial.prototype, "disableLighting", void 0);
  40785. __decorate([
  40786. BABYLON.serialize("useObjectSpaceNormalMap")
  40787. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40788. __decorate([
  40789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40790. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40791. __decorate([
  40792. BABYLON.serialize("useParallax")
  40793. ], StandardMaterial.prototype, "_useParallax", void 0);
  40794. __decorate([
  40795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40796. ], StandardMaterial.prototype, "useParallax", void 0);
  40797. __decorate([
  40798. BABYLON.serialize("useParallaxOcclusion")
  40799. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40800. __decorate([
  40801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40802. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40803. __decorate([
  40804. BABYLON.serialize()
  40805. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40806. __decorate([
  40807. BABYLON.serialize("roughness")
  40808. ], StandardMaterial.prototype, "_roughness", void 0);
  40809. __decorate([
  40810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40811. ], StandardMaterial.prototype, "roughness", void 0);
  40812. __decorate([
  40813. BABYLON.serialize()
  40814. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40815. __decorate([
  40816. BABYLON.serialize()
  40817. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40818. __decorate([
  40819. BABYLON.serialize("useLightmapAsShadowmap")
  40820. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40821. __decorate([
  40822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40823. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40824. __decorate([
  40825. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40826. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40827. __decorate([
  40828. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40829. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40830. __decorate([
  40831. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40832. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40833. __decorate([
  40834. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40835. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40836. __decorate([
  40837. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40838. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40839. __decorate([
  40840. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40841. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40842. __decorate([
  40843. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40844. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40845. __decorate([
  40846. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40847. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40848. __decorate([
  40849. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40850. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40851. __decorate([
  40852. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40853. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40854. __decorate([
  40855. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40856. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40857. __decorate([
  40858. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40859. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40860. __decorate([
  40861. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40862. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40863. __decorate([
  40864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40865. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40866. __decorate([
  40867. BABYLON.serialize("maxSimultaneousLights")
  40868. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40869. __decorate([
  40870. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40871. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40872. __decorate([
  40873. BABYLON.serialize("invertNormalMapX")
  40874. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40875. __decorate([
  40876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40877. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40878. __decorate([
  40879. BABYLON.serialize("invertNormalMapY")
  40880. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40881. __decorate([
  40882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40883. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40884. __decorate([
  40885. BABYLON.serialize("twoSidedLighting")
  40886. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40887. __decorate([
  40888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40889. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40890. __decorate([
  40891. BABYLON.serialize()
  40892. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40893. return StandardMaterial;
  40894. }(BABYLON.PushMaterial));
  40895. BABYLON.StandardMaterial = StandardMaterial;
  40896. })(BABYLON || (BABYLON = {}));
  40897. //# sourceMappingURL=babylon.standardMaterial.js.map
  40898. "use strict";
  40899. var BABYLON;
  40900. (function (BABYLON) {
  40901. /**
  40902. * Manages the defines for the PBR Material.
  40903. */
  40904. var PBRMaterialDefines = /** @class */ (function (_super) {
  40905. __extends(PBRMaterialDefines, _super);
  40906. /**
  40907. * Initializes the PBR Material defines.
  40908. */
  40909. function PBRMaterialDefines() {
  40910. var _this = _super.call(this) || this;
  40911. _this.PBR = true;
  40912. _this.MAINUV1 = false;
  40913. _this.MAINUV2 = false;
  40914. _this.UV1 = false;
  40915. _this.UV2 = false;
  40916. _this.ALBEDO = false;
  40917. _this.ALBEDODIRECTUV = 0;
  40918. _this.VERTEXCOLOR = false;
  40919. _this.AMBIENT = false;
  40920. _this.AMBIENTDIRECTUV = 0;
  40921. _this.AMBIENTINGRAYSCALE = false;
  40922. _this.OPACITY = false;
  40923. _this.VERTEXALPHA = false;
  40924. _this.OPACITYDIRECTUV = 0;
  40925. _this.OPACITYRGB = false;
  40926. _this.ALPHATEST = false;
  40927. _this.DEPTHPREPASS = false;
  40928. _this.ALPHABLEND = false;
  40929. _this.ALPHAFROMALBEDO = false;
  40930. _this.ALPHATESTVALUE = "0.5";
  40931. _this.SPECULAROVERALPHA = false;
  40932. _this.RADIANCEOVERALPHA = false;
  40933. _this.ALPHAFRESNEL = false;
  40934. _this.LINEARALPHAFRESNEL = false;
  40935. _this.PREMULTIPLYALPHA = false;
  40936. _this.EMISSIVE = false;
  40937. _this.EMISSIVEDIRECTUV = 0;
  40938. _this.REFLECTIVITY = false;
  40939. _this.REFLECTIVITYDIRECTUV = 0;
  40940. _this.SPECULARTERM = false;
  40941. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40942. _this.MICROSURFACEAUTOMATIC = false;
  40943. _this.LODBASEDMICROSFURACE = false;
  40944. _this.MICROSURFACEMAP = false;
  40945. _this.MICROSURFACEMAPDIRECTUV = 0;
  40946. _this.METALLICWORKFLOW = false;
  40947. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40948. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40949. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40950. _this.AOSTOREINMETALMAPRED = false;
  40951. _this.ENVIRONMENTBRDF = false;
  40952. _this.NORMAL = false;
  40953. _this.TANGENT = false;
  40954. _this.BUMP = false;
  40955. _this.BUMPDIRECTUV = 0;
  40956. _this.OBJECTSPACE_NORMALMAP = false;
  40957. _this.PARALLAX = false;
  40958. _this.PARALLAXOCCLUSION = false;
  40959. _this.NORMALXYSCALE = true;
  40960. _this.LIGHTMAP = false;
  40961. _this.LIGHTMAPDIRECTUV = 0;
  40962. _this.USELIGHTMAPASSHADOWMAP = false;
  40963. _this.GAMMALIGHTMAP = false;
  40964. _this.REFLECTION = false;
  40965. _this.REFLECTIONMAP_3D = false;
  40966. _this.REFLECTIONMAP_SPHERICAL = false;
  40967. _this.REFLECTIONMAP_PLANAR = false;
  40968. _this.REFLECTIONMAP_CUBIC = false;
  40969. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40970. _this.REFLECTIONMAP_PROJECTION = false;
  40971. _this.REFLECTIONMAP_SKYBOX = false;
  40972. _this.REFLECTIONMAP_EXPLICIT = false;
  40973. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40974. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40975. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40976. _this.INVERTCUBICMAP = false;
  40977. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40978. _this.USESPHERICALINVERTEX = false;
  40979. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40980. _this.LODINREFLECTIONALPHA = false;
  40981. _this.GAMMAREFLECTION = false;
  40982. _this.RADIANCEOCCLUSION = false;
  40983. _this.HORIZONOCCLUSION = false;
  40984. _this.REFRACTION = false;
  40985. _this.REFRACTIONMAP_3D = false;
  40986. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40987. _this.LODINREFRACTIONALPHA = false;
  40988. _this.GAMMAREFRACTION = false;
  40989. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40990. _this.INSTANCES = false;
  40991. _this.NUM_BONE_INFLUENCERS = 0;
  40992. _this.BonesPerMesh = 0;
  40993. _this.NONUNIFORMSCALING = false;
  40994. _this.MORPHTARGETS = false;
  40995. _this.MORPHTARGETS_NORMAL = false;
  40996. _this.MORPHTARGETS_TANGENT = false;
  40997. _this.NUM_MORPH_INFLUENCERS = 0;
  40998. _this.IMAGEPROCESSING = false;
  40999. _this.VIGNETTE = false;
  41000. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41001. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41002. _this.TONEMAPPING = false;
  41003. _this.CONTRAST = false;
  41004. _this.COLORCURVES = false;
  41005. _this.COLORGRADING = false;
  41006. _this.COLORGRADING3D = false;
  41007. _this.SAMPLER3DGREENDEPTH = false;
  41008. _this.SAMPLER3DBGRMAP = false;
  41009. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41010. _this.EXPOSURE = false;
  41011. _this.GRAIN = false;
  41012. _this.USEPHYSICALLIGHTFALLOFF = false;
  41013. _this.TWOSIDEDLIGHTING = false;
  41014. _this.SHADOWFLOAT = false;
  41015. _this.CLIPPLANE = false;
  41016. _this.POINTSIZE = false;
  41017. _this.FOG = false;
  41018. _this.LOGARITHMICDEPTH = false;
  41019. _this.FORCENORMALFORWARD = false;
  41020. _this.UNLIT = false;
  41021. _this.rebuild();
  41022. return _this;
  41023. }
  41024. /**
  41025. * Resets the PBR Material defines.
  41026. */
  41027. PBRMaterialDefines.prototype.reset = function () {
  41028. _super.prototype.reset.call(this);
  41029. this.ALPHATESTVALUE = "0.5";
  41030. this.PBR = true;
  41031. };
  41032. return PBRMaterialDefines;
  41033. }(BABYLON.MaterialDefines));
  41034. /**
  41035. * The Physically based material base class of BJS.
  41036. *
  41037. * This offers the main features of a standard PBR material.
  41038. * For more information, please refer to the documentation :
  41039. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41040. */
  41041. var PBRBaseMaterial = /** @class */ (function (_super) {
  41042. __extends(PBRBaseMaterial, _super);
  41043. /**
  41044. * Instantiates a new PBRMaterial instance.
  41045. *
  41046. * @param name The material name
  41047. * @param scene The scene the material will be use in.
  41048. */
  41049. function PBRBaseMaterial(name, scene) {
  41050. var _this = _super.call(this, name, scene) || this;
  41051. /**
  41052. * Intensity of the direct lights e.g. the four lights available in your scene.
  41053. * This impacts both the direct diffuse and specular highlights.
  41054. */
  41055. _this._directIntensity = 1.0;
  41056. /**
  41057. * Intensity of the emissive part of the material.
  41058. * This helps controlling the emissive effect without modifying the emissive color.
  41059. */
  41060. _this._emissiveIntensity = 1.0;
  41061. /**
  41062. * Intensity of the environment e.g. how much the environment will light the object
  41063. * either through harmonics for rough material or through the refelction for shiny ones.
  41064. */
  41065. _this._environmentIntensity = 1.0;
  41066. /**
  41067. * This is a special control allowing the reduction of the specular highlights coming from the
  41068. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41069. */
  41070. _this._specularIntensity = 1.0;
  41071. /**
  41072. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41073. */
  41074. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41075. /**
  41076. * Debug Control allowing disabling the bump map on this material.
  41077. */
  41078. _this._disableBumpMap = false;
  41079. /**
  41080. * AKA Occlusion Texture Intensity in other nomenclature.
  41081. */
  41082. _this._ambientTextureStrength = 1.0;
  41083. /**
  41084. * The color of a material in ambient lighting.
  41085. */
  41086. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41087. /**
  41088. * AKA Diffuse Color in other nomenclature.
  41089. */
  41090. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41091. /**
  41092. * AKA Specular Color in other nomenclature.
  41093. */
  41094. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41095. /**
  41096. * The color applied when light is reflected from a material.
  41097. */
  41098. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41099. /**
  41100. * The color applied when light is emitted from a material.
  41101. */
  41102. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41103. /**
  41104. * AKA Glossiness in other nomenclature.
  41105. */
  41106. _this._microSurface = 0.9;
  41107. /**
  41108. * source material index of refraction (IOR)' / 'destination material IOR.
  41109. */
  41110. _this._indexOfRefraction = 0.66;
  41111. /**
  41112. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41113. */
  41114. _this._invertRefractionY = false;
  41115. /**
  41116. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41117. * Materials half opaque for instance using refraction could benefit from this control.
  41118. */
  41119. _this._linkRefractionWithTransparency = false;
  41120. /**
  41121. * Specifies that the material will use the light map as a show map.
  41122. */
  41123. _this._useLightmapAsShadowmap = false;
  41124. /**
  41125. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41126. * makes the reflect vector face the model (under horizon).
  41127. */
  41128. _this._useHorizonOcclusion = true;
  41129. /**
  41130. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41131. * too much the area relying on ambient texture to define their ambient occlusion.
  41132. */
  41133. _this._useRadianceOcclusion = true;
  41134. /**
  41135. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41136. */
  41137. _this._useAlphaFromAlbedoTexture = false;
  41138. /**
  41139. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41140. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41141. */
  41142. _this._useSpecularOverAlpha = true;
  41143. /**
  41144. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41145. */
  41146. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41147. /**
  41148. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41149. */
  41150. _this._useRoughnessFromMetallicTextureAlpha = true;
  41151. /**
  41152. * Specifies if the metallic texture contains the roughness information in its green channel.
  41153. */
  41154. _this._useRoughnessFromMetallicTextureGreen = false;
  41155. /**
  41156. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41157. */
  41158. _this._useMetallnessFromMetallicTextureBlue = false;
  41159. /**
  41160. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41161. */
  41162. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41163. /**
  41164. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41165. */
  41166. _this._useAmbientInGrayScale = false;
  41167. /**
  41168. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41169. * The material will try to infer what glossiness each pixel should be.
  41170. */
  41171. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41172. /**
  41173. * BJS is using an harcoded light falloff based on a manually sets up range.
  41174. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41175. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41176. */
  41177. _this._usePhysicalLightFalloff = true;
  41178. /**
  41179. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41180. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41181. */
  41182. _this._useRadianceOverAlpha = true;
  41183. /**
  41184. * Allows using an object space normal map (instead of tangent space).
  41185. */
  41186. _this._useObjectSpaceNormalMap = false;
  41187. /**
  41188. * Allows using the bump map in parallax mode.
  41189. */
  41190. _this._useParallax = false;
  41191. /**
  41192. * Allows using the bump map in parallax occlusion mode.
  41193. */
  41194. _this._useParallaxOcclusion = false;
  41195. /**
  41196. * Controls the scale bias of the parallax mode.
  41197. */
  41198. _this._parallaxScaleBias = 0.05;
  41199. /**
  41200. * If sets to true, disables all the lights affecting the material.
  41201. */
  41202. _this._disableLighting = false;
  41203. /**
  41204. * Number of Simultaneous lights allowed on the material.
  41205. */
  41206. _this._maxSimultaneousLights = 4;
  41207. /**
  41208. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41209. */
  41210. _this._invertNormalMapX = false;
  41211. /**
  41212. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41213. */
  41214. _this._invertNormalMapY = false;
  41215. /**
  41216. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41217. */
  41218. _this._twoSidedLighting = false;
  41219. /**
  41220. * Defines the alpha limits in alpha test mode.
  41221. */
  41222. _this._alphaCutOff = 0.4;
  41223. /**
  41224. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41225. */
  41226. _this._forceAlphaTest = false;
  41227. /**
  41228. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41229. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41230. */
  41231. _this._useAlphaFresnel = false;
  41232. /**
  41233. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41234. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41235. */
  41236. _this._useLinearAlphaFresnel = false;
  41237. /**
  41238. * The transparency mode of the material.
  41239. */
  41240. _this._transparencyMode = null;
  41241. /**
  41242. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41243. * from cos thetav and roughness:
  41244. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41245. */
  41246. _this._environmentBRDFTexture = null;
  41247. /**
  41248. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41249. */
  41250. _this._forceIrradianceInFragment = false;
  41251. /**
  41252. * Force normal to face away from face.
  41253. */
  41254. _this._forceNormalForward = false;
  41255. /**
  41256. * Stores the available render targets.
  41257. */
  41258. _this._renderTargets = new BABYLON.SmartArray(16);
  41259. /**
  41260. * Sets the global ambient color for the material used in lighting calculations.
  41261. */
  41262. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41263. /**
  41264. * If set to true, no lighting calculations will be applied.
  41265. */
  41266. _this._unlit = false;
  41267. // Setup the default processing configuration to the scene.
  41268. _this._attachImageProcessingConfiguration(null);
  41269. _this.getRenderTargetTextures = function () {
  41270. _this._renderTargets.reset();
  41271. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41272. _this._renderTargets.push(_this._reflectionTexture);
  41273. }
  41274. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41275. _this._renderTargets.push(_this._refractionTexture);
  41276. }
  41277. return _this._renderTargets;
  41278. };
  41279. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41280. return _this;
  41281. }
  41282. /**
  41283. * Attaches a new image processing configuration to the PBR Material.
  41284. * @param configuration
  41285. */
  41286. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41287. var _this = this;
  41288. if (configuration === this._imageProcessingConfiguration) {
  41289. return;
  41290. }
  41291. // Detaches observer.
  41292. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41293. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41294. }
  41295. // Pick the scene configuration if needed.
  41296. if (!configuration) {
  41297. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41298. }
  41299. else {
  41300. this._imageProcessingConfiguration = configuration;
  41301. }
  41302. // Attaches observer.
  41303. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41304. _this._markAllSubMeshesAsImageProcessingDirty();
  41305. });
  41306. };
  41307. /**
  41308. * Gets the name of the material class.
  41309. */
  41310. PBRBaseMaterial.prototype.getClassName = function () {
  41311. return "PBRBaseMaterial";
  41312. };
  41313. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41314. /**
  41315. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41316. */
  41317. get: function () {
  41318. return this._useLogarithmicDepth;
  41319. },
  41320. /**
  41321. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41322. */
  41323. set: function (value) {
  41324. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41325. },
  41326. enumerable: true,
  41327. configurable: true
  41328. });
  41329. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41330. /**
  41331. * Gets the current transparency mode.
  41332. */
  41333. get: function () {
  41334. return this._transparencyMode;
  41335. },
  41336. /**
  41337. * Sets the transparency mode of the material.
  41338. */
  41339. set: function (value) {
  41340. if (this._transparencyMode === value) {
  41341. return;
  41342. }
  41343. this._transparencyMode = value;
  41344. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41345. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41346. },
  41347. enumerable: true,
  41348. configurable: true
  41349. });
  41350. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41351. /**
  41352. * Returns true if alpha blending should be disabled.
  41353. */
  41354. get: function () {
  41355. return (this._linkRefractionWithTransparency ||
  41356. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41357. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41358. },
  41359. enumerable: true,
  41360. configurable: true
  41361. });
  41362. /**
  41363. * Specifies whether or not this material should be rendered in alpha blend mode.
  41364. */
  41365. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41366. if (this._disableAlphaBlending) {
  41367. return false;
  41368. }
  41369. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41370. };
  41371. /**
  41372. * Specifies if the mesh will require alpha blending.
  41373. * @param mesh - BJS mesh.
  41374. */
  41375. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41376. if (this._disableAlphaBlending) {
  41377. return false;
  41378. }
  41379. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41380. };
  41381. /**
  41382. * Specifies whether or not this material should be rendered in alpha test mode.
  41383. */
  41384. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41385. if (this._forceAlphaTest) {
  41386. return true;
  41387. }
  41388. if (this._linkRefractionWithTransparency) {
  41389. return false;
  41390. }
  41391. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41392. };
  41393. /**
  41394. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41395. */
  41396. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41397. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41398. };
  41399. /**
  41400. * Gets the texture used for the alpha test.
  41401. */
  41402. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41403. return this._albedoTexture;
  41404. };
  41405. /**
  41406. * Specifies that the submesh is ready to be used.
  41407. * @param mesh - BJS mesh.
  41408. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41409. * @param useInstances - Specifies that instances should be used.
  41410. * @returns - boolean indicating that the submesh is ready or not.
  41411. */
  41412. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41413. if (subMesh.effect && this.isFrozen) {
  41414. if (this._wasPreviouslyReady) {
  41415. return true;
  41416. }
  41417. }
  41418. if (!subMesh._materialDefines) {
  41419. subMesh._materialDefines = new PBRMaterialDefines();
  41420. }
  41421. var defines = subMesh._materialDefines;
  41422. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41423. if (defines._renderId === this.getScene().getRenderId()) {
  41424. return true;
  41425. }
  41426. }
  41427. var scene = this.getScene();
  41428. var engine = scene.getEngine();
  41429. if (defines._areTexturesDirty) {
  41430. if (scene.texturesEnabled) {
  41431. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41432. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41433. return false;
  41434. }
  41435. }
  41436. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41437. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41438. return false;
  41439. }
  41440. }
  41441. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41442. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41443. return false;
  41444. }
  41445. }
  41446. var reflectionTexture = this._getReflectionTexture();
  41447. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41448. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41449. return false;
  41450. }
  41451. }
  41452. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41453. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41454. return false;
  41455. }
  41456. }
  41457. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41458. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41459. return false;
  41460. }
  41461. }
  41462. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41463. if (this._metallicTexture) {
  41464. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41465. return false;
  41466. }
  41467. }
  41468. else if (this._reflectivityTexture) {
  41469. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41470. return false;
  41471. }
  41472. }
  41473. if (this._microSurfaceTexture) {
  41474. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41475. return false;
  41476. }
  41477. }
  41478. }
  41479. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41480. // Bump texture cannot be not blocking.
  41481. if (!this._bumpTexture.isReady()) {
  41482. return false;
  41483. }
  41484. }
  41485. var refractionTexture = this._getRefractionTexture();
  41486. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41487. if (!refractionTexture.isReadyOrNotBlocking()) {
  41488. return false;
  41489. }
  41490. }
  41491. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41492. // This is blocking.
  41493. if (!this._environmentBRDFTexture.isReady()) {
  41494. return false;
  41495. }
  41496. }
  41497. }
  41498. }
  41499. if (defines._areImageProcessingDirty) {
  41500. if (!this._imageProcessingConfiguration.isReady()) {
  41501. return false;
  41502. }
  41503. }
  41504. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41505. mesh.createNormals(true);
  41506. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41507. }
  41508. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41509. if (effect) {
  41510. scene.resetCachedMaterial();
  41511. subMesh.setEffect(effect, defines);
  41512. this.buildUniformLayout();
  41513. }
  41514. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41515. return false;
  41516. }
  41517. defines._renderId = scene.getRenderId();
  41518. this._wasPreviouslyReady = true;
  41519. return true;
  41520. };
  41521. /**
  41522. * Specifies if the material uses metallic roughness workflow.
  41523. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41524. */
  41525. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41526. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41527. return true;
  41528. }
  41529. return false;
  41530. };
  41531. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41532. if (onCompiled === void 0) { onCompiled = null; }
  41533. if (onError === void 0) { onError = null; }
  41534. if (useInstances === void 0) { useInstances = null; }
  41535. if (useClipPlane === void 0) { useClipPlane = null; }
  41536. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41537. if (!defines.isDirty) {
  41538. return null;
  41539. }
  41540. defines.markAsProcessed();
  41541. var scene = this.getScene();
  41542. var engine = scene.getEngine();
  41543. // Fallbacks
  41544. var fallbacks = new BABYLON.EffectFallbacks();
  41545. var fallbackRank = 0;
  41546. if (defines.USESPHERICALINVERTEX) {
  41547. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41548. }
  41549. if (defines.FOG) {
  41550. fallbacks.addFallback(fallbackRank, "FOG");
  41551. }
  41552. if (defines.POINTSIZE) {
  41553. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41554. }
  41555. if (defines.LOGARITHMICDEPTH) {
  41556. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41557. }
  41558. if (defines.PARALLAX) {
  41559. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41560. }
  41561. if (defines.PARALLAXOCCLUSION) {
  41562. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41563. }
  41564. if (defines.ENVIRONMENTBRDF) {
  41565. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41566. }
  41567. if (defines.TANGENT) {
  41568. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41569. }
  41570. if (defines.BUMP) {
  41571. fallbacks.addFallback(fallbackRank++, "BUMP");
  41572. }
  41573. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41574. if (defines.SPECULARTERM) {
  41575. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41576. }
  41577. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41578. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41579. }
  41580. if (defines.LIGHTMAP) {
  41581. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41582. }
  41583. if (defines.NORMAL) {
  41584. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41585. }
  41586. if (defines.AMBIENT) {
  41587. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41588. }
  41589. if (defines.EMISSIVE) {
  41590. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41591. }
  41592. if (defines.VERTEXCOLOR) {
  41593. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41594. }
  41595. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41596. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41597. }
  41598. if (defines.MORPHTARGETS) {
  41599. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41600. }
  41601. //Attributes
  41602. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41603. if (defines.NORMAL) {
  41604. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41605. }
  41606. if (defines.TANGENT) {
  41607. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41608. }
  41609. if (defines.UV1) {
  41610. attribs.push(BABYLON.VertexBuffer.UVKind);
  41611. }
  41612. if (defines.UV2) {
  41613. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41614. }
  41615. if (defines.VERTEXCOLOR) {
  41616. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41617. }
  41618. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41619. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41620. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41621. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41622. "vFogInfos", "vFogColor", "pointSize",
  41623. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41624. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41625. "mBones",
  41626. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41627. "vLightingIntensity",
  41628. "logarithmicDepthConstant",
  41629. "vSphericalX", "vSphericalY", "vSphericalZ",
  41630. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41631. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41632. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41633. "vTangentSpaceParams"
  41634. ];
  41635. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41636. "bumpSampler", "lightmapSampler", "opacitySampler",
  41637. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41638. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41639. "microSurfaceSampler", "environmentBrdfSampler"];
  41640. var uniformBuffers = ["Material", "Scene"];
  41641. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41642. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41643. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41644. uniformsNames: uniforms,
  41645. uniformBuffersNames: uniformBuffers,
  41646. samplers: samplers,
  41647. defines: defines,
  41648. maxSimultaneousLights: this._maxSimultaneousLights
  41649. });
  41650. var join = defines.toString();
  41651. return engine.createEffect("pbr", {
  41652. attributes: attribs,
  41653. uniformsNames: uniforms,
  41654. uniformBuffersNames: uniformBuffers,
  41655. samplers: samplers,
  41656. defines: join,
  41657. fallbacks: fallbacks,
  41658. onCompiled: onCompiled,
  41659. onError: onError,
  41660. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41661. }, engine);
  41662. };
  41663. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41664. if (useInstances === void 0) { useInstances = null; }
  41665. if (useClipPlane === void 0) { useClipPlane = null; }
  41666. var scene = this.getScene();
  41667. var engine = scene.getEngine();
  41668. // Lights
  41669. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41670. defines._needNormals = true;
  41671. // Textures
  41672. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41673. if (defines._areTexturesDirty) {
  41674. defines._needUVs = false;
  41675. if (scene.texturesEnabled) {
  41676. if (scene.getEngine().getCaps().textureLOD) {
  41677. defines.LODBASEDMICROSFURACE = true;
  41678. }
  41679. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41680. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41681. }
  41682. else {
  41683. defines.ALBEDO = false;
  41684. }
  41685. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41686. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41687. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41688. }
  41689. else {
  41690. defines.AMBIENT = false;
  41691. }
  41692. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41693. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41694. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41695. }
  41696. else {
  41697. defines.OPACITY = false;
  41698. }
  41699. var reflectionTexture = this._getReflectionTexture();
  41700. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41701. defines.REFLECTION = true;
  41702. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41703. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41704. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41705. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41706. defines.INVERTCUBICMAP = true;
  41707. }
  41708. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41709. switch (reflectionTexture.coordinatesMode) {
  41710. case BABYLON.Texture.CUBIC_MODE:
  41711. case BABYLON.Texture.INVCUBIC_MODE:
  41712. defines.REFLECTIONMAP_CUBIC = true;
  41713. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41714. break;
  41715. case BABYLON.Texture.EXPLICIT_MODE:
  41716. defines.REFLECTIONMAP_EXPLICIT = true;
  41717. break;
  41718. case BABYLON.Texture.PLANAR_MODE:
  41719. defines.REFLECTIONMAP_PLANAR = true;
  41720. break;
  41721. case BABYLON.Texture.PROJECTION_MODE:
  41722. defines.REFLECTIONMAP_PROJECTION = true;
  41723. break;
  41724. case BABYLON.Texture.SKYBOX_MODE:
  41725. defines.REFLECTIONMAP_SKYBOX = true;
  41726. break;
  41727. case BABYLON.Texture.SPHERICAL_MODE:
  41728. defines.REFLECTIONMAP_SPHERICAL = true;
  41729. break;
  41730. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41731. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41732. break;
  41733. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41734. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41735. break;
  41736. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41737. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41738. break;
  41739. }
  41740. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41741. if (reflectionTexture.sphericalPolynomial) {
  41742. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41743. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41744. defines.USESPHERICALINVERTEX = false;
  41745. }
  41746. else {
  41747. defines.USESPHERICALINVERTEX = true;
  41748. }
  41749. }
  41750. }
  41751. }
  41752. else {
  41753. defines.REFLECTION = false;
  41754. defines.REFLECTIONMAP_3D = false;
  41755. defines.REFLECTIONMAP_SPHERICAL = false;
  41756. defines.REFLECTIONMAP_PLANAR = false;
  41757. defines.REFLECTIONMAP_CUBIC = false;
  41758. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41759. defines.REFLECTIONMAP_PROJECTION = false;
  41760. defines.REFLECTIONMAP_SKYBOX = false;
  41761. defines.REFLECTIONMAP_EXPLICIT = false;
  41762. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41763. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41764. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41765. defines.INVERTCUBICMAP = false;
  41766. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41767. defines.USESPHERICALINVERTEX = false;
  41768. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41769. defines.LODINREFLECTIONALPHA = false;
  41770. defines.GAMMAREFLECTION = false;
  41771. }
  41772. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41773. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41774. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41775. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41776. }
  41777. else {
  41778. defines.LIGHTMAP = false;
  41779. }
  41780. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41781. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41782. }
  41783. else {
  41784. defines.EMISSIVE = false;
  41785. }
  41786. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41787. if (this._metallicTexture) {
  41788. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41789. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41790. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41791. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41792. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41793. }
  41794. else if (this._reflectivityTexture) {
  41795. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41796. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41797. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41798. }
  41799. else {
  41800. defines.REFLECTIVITY = false;
  41801. }
  41802. if (this._microSurfaceTexture) {
  41803. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41804. }
  41805. else {
  41806. defines.MICROSURFACEMAP = false;
  41807. }
  41808. }
  41809. else {
  41810. defines.REFLECTIVITY = false;
  41811. defines.MICROSURFACEMAP = false;
  41812. }
  41813. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41814. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41815. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41816. defines.PARALLAX = true;
  41817. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41818. }
  41819. else {
  41820. defines.PARALLAX = false;
  41821. }
  41822. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41823. }
  41824. else {
  41825. defines.BUMP = false;
  41826. }
  41827. var refractionTexture = this._getRefractionTexture();
  41828. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41829. defines.REFRACTION = true;
  41830. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41831. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41832. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41833. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41834. if (this._linkRefractionWithTransparency) {
  41835. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41836. }
  41837. }
  41838. else {
  41839. defines.REFRACTION = false;
  41840. }
  41841. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41842. defines.ENVIRONMENTBRDF = true;
  41843. }
  41844. else {
  41845. defines.ENVIRONMENTBRDF = false;
  41846. }
  41847. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41848. defines.ALPHAFROMALBEDO = true;
  41849. }
  41850. else {
  41851. defines.ALPHAFROMALBEDO = false;
  41852. }
  41853. }
  41854. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41855. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41856. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41857. if (!this.backFaceCulling && this._twoSidedLighting) {
  41858. defines.TWOSIDEDLIGHTING = true;
  41859. }
  41860. else {
  41861. defines.TWOSIDEDLIGHTING = false;
  41862. }
  41863. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41864. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41865. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41866. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41867. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41868. }
  41869. if (defines._areImageProcessingDirty) {
  41870. this._imageProcessingConfiguration.prepareDefines(defines);
  41871. }
  41872. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41873. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41874. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41875. // Misc.
  41876. if (defines._areMiscDirty) {
  41877. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41878. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41879. }
  41880. // Values that need to be evaluated on every frame
  41881. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41882. // Attribs
  41883. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41884. };
  41885. /**
  41886. * Force shader compilation
  41887. */
  41888. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41889. var _this = this;
  41890. var localOptions = __assign({ clipPlane: false }, options);
  41891. var defines = new PBRMaterialDefines();
  41892. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41893. if (effect.isReady()) {
  41894. if (onCompiled) {
  41895. onCompiled(this);
  41896. }
  41897. }
  41898. else {
  41899. effect.onCompileObservable.add(function () {
  41900. if (onCompiled) {
  41901. onCompiled(_this);
  41902. }
  41903. });
  41904. }
  41905. };
  41906. /**
  41907. * Initializes the uniform buffer layout for the shader.
  41908. */
  41909. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41910. // Order is important !
  41911. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41912. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41913. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41914. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41915. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41916. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41917. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41918. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41919. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41920. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41921. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41922. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41923. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41924. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41925. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41926. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41927. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41928. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41929. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41930. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41931. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41932. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41933. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41934. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41935. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41936. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41937. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41938. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41939. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41940. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41941. this._uniformBuffer.addUniform("pointSize", 1);
  41942. this._uniformBuffer.create();
  41943. };
  41944. /**
  41945. * Unbinds the textures.
  41946. */
  41947. PBRBaseMaterial.prototype.unbind = function () {
  41948. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41949. this._uniformBuffer.setTexture("reflectionSampler", null);
  41950. }
  41951. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41952. this._uniformBuffer.setTexture("refractionSampler", null);
  41953. }
  41954. _super.prototype.unbind.call(this);
  41955. };
  41956. /**
  41957. * Binds the submesh data.
  41958. * @param world - The world matrix.
  41959. * @param mesh - The BJS mesh.
  41960. * @param subMesh - A submesh of the BJS mesh.
  41961. */
  41962. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41963. var scene = this.getScene();
  41964. var defines = subMesh._materialDefines;
  41965. if (!defines) {
  41966. return;
  41967. }
  41968. var effect = subMesh.effect;
  41969. if (!effect) {
  41970. return;
  41971. }
  41972. this._activeEffect = effect;
  41973. // Matrices
  41974. this.bindOnlyWorldMatrix(world);
  41975. // Normal Matrix
  41976. if (defines.OBJECTSPACE_NORMALMAP) {
  41977. world.toNormalMatrix(this._normalMatrix);
  41978. this.bindOnlyNormalMatrix(this._normalMatrix);
  41979. }
  41980. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41981. // Bones
  41982. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41983. var reflectionTexture = null;
  41984. if (mustRebind) {
  41985. this._uniformBuffer.bindToEffect(effect, "Material");
  41986. this.bindViewProjection(effect);
  41987. reflectionTexture = this._getReflectionTexture();
  41988. var refractionTexture = this._getRefractionTexture();
  41989. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41990. // Texture uniforms
  41991. if (scene.texturesEnabled) {
  41992. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41993. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41994. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41995. }
  41996. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41997. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41998. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41999. }
  42000. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42001. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42002. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42003. }
  42004. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42005. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  42006. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  42007. if (reflectionTexture.boundingBoxSize) {
  42008. var cubeTexture = reflectionTexture;
  42009. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42010. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42011. }
  42012. var polynomials = reflectionTexture.sphericalPolynomial;
  42013. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  42014. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  42015. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  42016. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  42017. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  42018. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  42019. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  42020. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  42021. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  42022. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  42023. }
  42024. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  42025. }
  42026. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42027. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42028. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42029. }
  42030. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42031. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42032. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42033. }
  42034. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42035. if (this._metallicTexture) {
  42036. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42037. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42038. }
  42039. else if (this._reflectivityTexture) {
  42040. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42041. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42042. }
  42043. if (this._microSurfaceTexture) {
  42044. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42045. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42046. }
  42047. }
  42048. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42049. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42050. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42051. if (scene._mirroredCameraPosition) {
  42052. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42053. }
  42054. else {
  42055. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42056. }
  42057. }
  42058. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42059. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42060. var depth = 1.0;
  42061. if (!refractionTexture.isCube) {
  42062. if (refractionTexture.depth) {
  42063. depth = refractionTexture.depth;
  42064. }
  42065. }
  42066. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42067. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42068. }
  42069. }
  42070. // Point size
  42071. if (this.pointsCloud) {
  42072. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42073. }
  42074. // Colors
  42075. if (defines.METALLICWORKFLOW) {
  42076. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42077. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42078. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42079. }
  42080. else {
  42081. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42082. }
  42083. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42084. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42085. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42086. // Misc
  42087. this._lightingInfos.x = this._directIntensity;
  42088. this._lightingInfos.y = this._emissiveIntensity;
  42089. this._lightingInfos.z = this._environmentIntensity;
  42090. this._lightingInfos.w = this._specularIntensity;
  42091. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42092. }
  42093. // Textures
  42094. if (scene.texturesEnabled) {
  42095. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42096. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42097. }
  42098. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42099. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42100. }
  42101. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42102. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42103. }
  42104. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42105. if (defines.LODBASEDMICROSFURACE) {
  42106. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42107. }
  42108. else {
  42109. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42110. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42111. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42112. }
  42113. }
  42114. if (defines.ENVIRONMENTBRDF) {
  42115. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42116. }
  42117. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42118. if (defines.LODBASEDMICROSFURACE) {
  42119. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42120. }
  42121. else {
  42122. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42123. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42124. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42125. }
  42126. }
  42127. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42128. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42129. }
  42130. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42131. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42132. }
  42133. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42134. if (this._metallicTexture) {
  42135. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42136. }
  42137. else if (this._reflectivityTexture) {
  42138. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42139. }
  42140. if (this._microSurfaceTexture) {
  42141. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42142. }
  42143. }
  42144. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42145. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42146. }
  42147. }
  42148. // Clip plane
  42149. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42150. // Colors
  42151. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42152. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42153. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42154. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42155. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42156. }
  42157. if (mustRebind || !this.isFrozen) {
  42158. // Lights
  42159. if (scene.lightsEnabled && !this._disableLighting) {
  42160. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42161. }
  42162. // View
  42163. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42164. this.bindView(effect);
  42165. }
  42166. // Fog
  42167. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42168. // Morph targets
  42169. if (defines.NUM_MORPH_INFLUENCERS) {
  42170. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42171. }
  42172. // image processing
  42173. this._imageProcessingConfiguration.bind(this._activeEffect);
  42174. // Log. depth
  42175. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42176. }
  42177. this._uniformBuffer.update();
  42178. this._afterBind(mesh);
  42179. };
  42180. /**
  42181. * Returns the animatable textures.
  42182. * @returns - Array of animatable textures.
  42183. */
  42184. PBRBaseMaterial.prototype.getAnimatables = function () {
  42185. var results = [];
  42186. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42187. results.push(this._albedoTexture);
  42188. }
  42189. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42190. results.push(this._ambientTexture);
  42191. }
  42192. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42193. results.push(this._opacityTexture);
  42194. }
  42195. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42196. results.push(this._reflectionTexture);
  42197. }
  42198. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42199. results.push(this._emissiveTexture);
  42200. }
  42201. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42202. results.push(this._metallicTexture);
  42203. }
  42204. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42205. results.push(this._reflectivityTexture);
  42206. }
  42207. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42208. results.push(this._bumpTexture);
  42209. }
  42210. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42211. results.push(this._lightmapTexture);
  42212. }
  42213. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42214. results.push(this._refractionTexture);
  42215. }
  42216. return results;
  42217. };
  42218. /**
  42219. * Returns the texture used for reflections.
  42220. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42221. */
  42222. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42223. if (this._reflectionTexture) {
  42224. return this._reflectionTexture;
  42225. }
  42226. return this.getScene().environmentTexture;
  42227. };
  42228. /**
  42229. * Returns the texture used for refraction or null if none is used.
  42230. * @returns - Refection texture if present. If no refraction texture and refraction
  42231. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42232. */
  42233. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42234. if (this._refractionTexture) {
  42235. return this._refractionTexture;
  42236. }
  42237. if (this._linkRefractionWithTransparency) {
  42238. return this.getScene().environmentTexture;
  42239. }
  42240. return null;
  42241. };
  42242. /**
  42243. * Disposes the resources of the material.
  42244. * @param forceDisposeEffect - Forces the disposal of effects.
  42245. * @param forceDisposeTextures - Forces the disposal of all textures.
  42246. */
  42247. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42248. if (forceDisposeTextures) {
  42249. if (this._albedoTexture) {
  42250. this._albedoTexture.dispose();
  42251. }
  42252. if (this._ambientTexture) {
  42253. this._ambientTexture.dispose();
  42254. }
  42255. if (this._opacityTexture) {
  42256. this._opacityTexture.dispose();
  42257. }
  42258. if (this._reflectionTexture) {
  42259. this._reflectionTexture.dispose();
  42260. }
  42261. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42262. this._environmentBRDFTexture.dispose();
  42263. }
  42264. if (this._emissiveTexture) {
  42265. this._emissiveTexture.dispose();
  42266. }
  42267. if (this._metallicTexture) {
  42268. this._metallicTexture.dispose();
  42269. }
  42270. if (this._reflectivityTexture) {
  42271. this._reflectivityTexture.dispose();
  42272. }
  42273. if (this._bumpTexture) {
  42274. this._bumpTexture.dispose();
  42275. }
  42276. if (this._lightmapTexture) {
  42277. this._lightmapTexture.dispose();
  42278. }
  42279. if (this._refractionTexture) {
  42280. this._refractionTexture.dispose();
  42281. }
  42282. }
  42283. this._renderTargets.dispose();
  42284. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42285. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42286. }
  42287. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42288. };
  42289. /**
  42290. * Stores the reflectivity values based on metallic roughness workflow.
  42291. */
  42292. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42293. __decorate([
  42294. BABYLON.serializeAsImageProcessingConfiguration()
  42295. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42296. __decorate([
  42297. BABYLON.serialize()
  42298. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42299. __decorate([
  42300. BABYLON.serialize()
  42301. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42302. return PBRBaseMaterial;
  42303. }(BABYLON.PushMaterial));
  42304. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42305. })(BABYLON || (BABYLON = {}));
  42306. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42307. "use strict";
  42308. var BABYLON;
  42309. (function (BABYLON) {
  42310. /**
  42311. * The Physically based simple base material of BJS.
  42312. *
  42313. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42314. * It is used as the base class for both the specGloss and metalRough conventions.
  42315. */
  42316. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42317. __extends(PBRBaseSimpleMaterial, _super);
  42318. /**
  42319. * Instantiates a new PBRMaterial instance.
  42320. *
  42321. * @param name The material name
  42322. * @param scene The scene the material will be use in.
  42323. */
  42324. function PBRBaseSimpleMaterial(name, scene) {
  42325. var _this = _super.call(this, name, scene) || this;
  42326. /**
  42327. * Number of Simultaneous lights allowed on the material.
  42328. */
  42329. _this.maxSimultaneousLights = 4;
  42330. /**
  42331. * If sets to true, disables all the lights affecting the material.
  42332. */
  42333. _this.disableLighting = false;
  42334. /**
  42335. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42336. */
  42337. _this.invertNormalMapX = false;
  42338. /**
  42339. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42340. */
  42341. _this.invertNormalMapY = false;
  42342. /**
  42343. * Emissivie color used to self-illuminate the model.
  42344. */
  42345. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42346. /**
  42347. * Occlusion Channel Strenght.
  42348. */
  42349. _this.occlusionStrength = 1.0;
  42350. _this.useLightmapAsShadowmap = false;
  42351. _this._useAlphaFromAlbedoTexture = true;
  42352. _this._useAmbientInGrayScale = true;
  42353. return _this;
  42354. }
  42355. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42356. /**
  42357. * Gets the current double sided mode.
  42358. */
  42359. get: function () {
  42360. return this._twoSidedLighting;
  42361. },
  42362. /**
  42363. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42364. */
  42365. set: function (value) {
  42366. if (this._twoSidedLighting === value) {
  42367. return;
  42368. }
  42369. this._twoSidedLighting = value;
  42370. this.backFaceCulling = !value;
  42371. this._markAllSubMeshesAsTexturesDirty();
  42372. },
  42373. enumerable: true,
  42374. configurable: true
  42375. });
  42376. /**
  42377. * Return the active textures of the material.
  42378. */
  42379. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42380. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42381. if (this.environmentTexture) {
  42382. activeTextures.push(this.environmentTexture);
  42383. }
  42384. if (this.normalTexture) {
  42385. activeTextures.push(this.normalTexture);
  42386. }
  42387. if (this.emissiveTexture) {
  42388. activeTextures.push(this.emissiveTexture);
  42389. }
  42390. if (this.occlusionTexture) {
  42391. activeTextures.push(this.occlusionTexture);
  42392. }
  42393. if (this.lightmapTexture) {
  42394. activeTextures.push(this.lightmapTexture);
  42395. }
  42396. return activeTextures;
  42397. };
  42398. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42399. if (_super.prototype.hasTexture.call(this, texture)) {
  42400. return true;
  42401. }
  42402. if (this.lightmapTexture === texture) {
  42403. return true;
  42404. }
  42405. return false;
  42406. };
  42407. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42408. return "PBRBaseSimpleMaterial";
  42409. };
  42410. __decorate([
  42411. BABYLON.serialize(),
  42412. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42413. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42414. __decorate([
  42415. BABYLON.serialize(),
  42416. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42417. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42418. __decorate([
  42419. BABYLON.serializeAsTexture(),
  42420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42421. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42422. __decorate([
  42423. BABYLON.serialize(),
  42424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42425. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42426. __decorate([
  42427. BABYLON.serialize(),
  42428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42429. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42430. __decorate([
  42431. BABYLON.serializeAsTexture(),
  42432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42433. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42434. __decorate([
  42435. BABYLON.serializeAsColor3("emissive"),
  42436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42437. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42438. __decorate([
  42439. BABYLON.serializeAsTexture(),
  42440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42441. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42442. __decorate([
  42443. BABYLON.serialize(),
  42444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42445. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42446. __decorate([
  42447. BABYLON.serializeAsTexture(),
  42448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42449. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42450. __decorate([
  42451. BABYLON.serialize(),
  42452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42453. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42454. __decorate([
  42455. BABYLON.serialize()
  42456. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42457. __decorate([
  42458. BABYLON.serializeAsTexture(),
  42459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42460. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42461. __decorate([
  42462. BABYLON.serialize(),
  42463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42464. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42465. return PBRBaseSimpleMaterial;
  42466. }(BABYLON.PBRBaseMaterial));
  42467. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42468. })(BABYLON || (BABYLON = {}));
  42469. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42470. "use strict";
  42471. var BABYLON;
  42472. (function (BABYLON) {
  42473. /**
  42474. * The Physically based material of BJS.
  42475. *
  42476. * This offers the main features of a standard PBR material.
  42477. * For more information, please refer to the documentation :
  42478. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42479. */
  42480. var PBRMaterial = /** @class */ (function (_super) {
  42481. __extends(PBRMaterial, _super);
  42482. /**
  42483. * Instantiates a new PBRMaterial instance.
  42484. *
  42485. * @param name The material name
  42486. * @param scene The scene the material will be use in.
  42487. */
  42488. function PBRMaterial(name, scene) {
  42489. var _this = _super.call(this, name, scene) || this;
  42490. /**
  42491. * Intensity of the direct lights e.g. the four lights available in your scene.
  42492. * This impacts both the direct diffuse and specular highlights.
  42493. */
  42494. _this.directIntensity = 1.0;
  42495. /**
  42496. * Intensity of the emissive part of the material.
  42497. * This helps controlling the emissive effect without modifying the emissive color.
  42498. */
  42499. _this.emissiveIntensity = 1.0;
  42500. /**
  42501. * Intensity of the environment e.g. how much the environment will light the object
  42502. * either through harmonics for rough material or through the refelction for shiny ones.
  42503. */
  42504. _this.environmentIntensity = 1.0;
  42505. /**
  42506. * This is a special control allowing the reduction of the specular highlights coming from the
  42507. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42508. */
  42509. _this.specularIntensity = 1.0;
  42510. /**
  42511. * Debug Control allowing disabling the bump map on this material.
  42512. */
  42513. _this.disableBumpMap = false;
  42514. /**
  42515. * AKA Occlusion Texture Intensity in other nomenclature.
  42516. */
  42517. _this.ambientTextureStrength = 1.0;
  42518. /**
  42519. * The color of a material in ambient lighting.
  42520. */
  42521. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42522. /**
  42523. * AKA Diffuse Color in other nomenclature.
  42524. */
  42525. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42526. /**
  42527. * AKA Specular Color in other nomenclature.
  42528. */
  42529. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42530. /**
  42531. * The color reflected from the material.
  42532. */
  42533. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42534. /**
  42535. * The color emitted from the material.
  42536. */
  42537. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42538. /**
  42539. * AKA Glossiness in other nomenclature.
  42540. */
  42541. _this.microSurface = 1.0;
  42542. /**
  42543. * source material index of refraction (IOR)' / 'destination material IOR.
  42544. */
  42545. _this.indexOfRefraction = 0.66;
  42546. /**
  42547. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42548. */
  42549. _this.invertRefractionY = false;
  42550. /**
  42551. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42552. * Materials half opaque for instance using refraction could benefit from this control.
  42553. */
  42554. _this.linkRefractionWithTransparency = false;
  42555. _this.useLightmapAsShadowmap = false;
  42556. /**
  42557. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42558. */
  42559. _this.useAlphaFromAlbedoTexture = false;
  42560. /**
  42561. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42562. */
  42563. _this.forceAlphaTest = false;
  42564. /**
  42565. * Defines the alpha limits in alpha test mode.
  42566. */
  42567. _this.alphaCutOff = 0.4;
  42568. /**
  42569. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42570. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42571. */
  42572. _this.useSpecularOverAlpha = true;
  42573. /**
  42574. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42575. */
  42576. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42577. /**
  42578. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42579. */
  42580. _this.useRoughnessFromMetallicTextureAlpha = true;
  42581. /**
  42582. * Specifies if the metallic texture contains the roughness information in its green channel.
  42583. */
  42584. _this.useRoughnessFromMetallicTextureGreen = false;
  42585. /**
  42586. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42587. */
  42588. _this.useMetallnessFromMetallicTextureBlue = false;
  42589. /**
  42590. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42591. */
  42592. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42593. /**
  42594. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42595. */
  42596. _this.useAmbientInGrayScale = false;
  42597. /**
  42598. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42599. * The material will try to infer what glossiness each pixel should be.
  42600. */
  42601. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42602. /**
  42603. * BJS is using an harcoded light falloff based on a manually sets up range.
  42604. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42605. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42606. */
  42607. _this.usePhysicalLightFalloff = true;
  42608. /**
  42609. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42610. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42611. */
  42612. _this.useRadianceOverAlpha = true;
  42613. /**
  42614. * Allows using an object space normal map (instead of tangent space).
  42615. */
  42616. _this.useObjectSpaceNormalMap = false;
  42617. /**
  42618. * Allows using the bump map in parallax mode.
  42619. */
  42620. _this.useParallax = false;
  42621. /**
  42622. * Allows using the bump map in parallax occlusion mode.
  42623. */
  42624. _this.useParallaxOcclusion = false;
  42625. /**
  42626. * Controls the scale bias of the parallax mode.
  42627. */
  42628. _this.parallaxScaleBias = 0.05;
  42629. /**
  42630. * If sets to true, disables all the lights affecting the material.
  42631. */
  42632. _this.disableLighting = false;
  42633. /**
  42634. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42635. */
  42636. _this.forceIrradianceInFragment = false;
  42637. /**
  42638. * Number of Simultaneous lights allowed on the material.
  42639. */
  42640. _this.maxSimultaneousLights = 4;
  42641. /**
  42642. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42643. */
  42644. _this.invertNormalMapX = false;
  42645. /**
  42646. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42647. */
  42648. _this.invertNormalMapY = false;
  42649. /**
  42650. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42651. */
  42652. _this.twoSidedLighting = false;
  42653. /**
  42654. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42655. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42656. */
  42657. _this.useAlphaFresnel = false;
  42658. /**
  42659. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42660. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42661. */
  42662. _this.useLinearAlphaFresnel = false;
  42663. /**
  42664. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42665. * And/Or occlude the blended part.
  42666. */
  42667. _this.environmentBRDFTexture = null;
  42668. /**
  42669. * Force normal to face away from face.
  42670. */
  42671. _this.forceNormalForward = false;
  42672. /**
  42673. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42674. * makes the reflect vector face the model (under horizon).
  42675. */
  42676. _this.useHorizonOcclusion = true;
  42677. /**
  42678. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42679. * too much the area relying on ambient texture to define their ambient occlusion.
  42680. */
  42681. _this.useRadianceOcclusion = true;
  42682. /**
  42683. * If set to true, no lighting calculations will be applied.
  42684. */
  42685. _this.unlit = false;
  42686. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42687. return _this;
  42688. }
  42689. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42690. /**
  42691. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42692. */
  42693. get: function () {
  42694. return this._PBRMATERIAL_OPAQUE;
  42695. },
  42696. enumerable: true,
  42697. configurable: true
  42698. });
  42699. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42700. /**
  42701. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42702. */
  42703. get: function () {
  42704. return this._PBRMATERIAL_ALPHATEST;
  42705. },
  42706. enumerable: true,
  42707. configurable: true
  42708. });
  42709. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42710. /**
  42711. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42712. */
  42713. get: function () {
  42714. return this._PBRMATERIAL_ALPHABLEND;
  42715. },
  42716. enumerable: true,
  42717. configurable: true
  42718. });
  42719. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42720. /**
  42721. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42722. * They are also discarded below the alpha cutoff threshold to improve performances.
  42723. */
  42724. get: function () {
  42725. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42726. },
  42727. enumerable: true,
  42728. configurable: true
  42729. });
  42730. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42731. /**
  42732. * Gets the image processing configuration used either in this material.
  42733. */
  42734. get: function () {
  42735. return this._imageProcessingConfiguration;
  42736. },
  42737. /**
  42738. * Sets the Default image processing configuration used either in the this material.
  42739. *
  42740. * If sets to null, the scene one is in use.
  42741. */
  42742. set: function (value) {
  42743. this._attachImageProcessingConfiguration(value);
  42744. // Ensure the effect will be rebuilt.
  42745. this._markAllSubMeshesAsTexturesDirty();
  42746. },
  42747. enumerable: true,
  42748. configurable: true
  42749. });
  42750. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42751. /**
  42752. * Gets wether the color curves effect is enabled.
  42753. */
  42754. get: function () {
  42755. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42756. },
  42757. /**
  42758. * Sets wether the color curves effect is enabled.
  42759. */
  42760. set: function (value) {
  42761. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42762. },
  42763. enumerable: true,
  42764. configurable: true
  42765. });
  42766. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42767. /**
  42768. * Gets wether the color grading effect is enabled.
  42769. */
  42770. get: function () {
  42771. return this.imageProcessingConfiguration.colorGradingEnabled;
  42772. },
  42773. /**
  42774. * Gets wether the color grading effect is enabled.
  42775. */
  42776. set: function (value) {
  42777. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42778. },
  42779. enumerable: true,
  42780. configurable: true
  42781. });
  42782. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42783. /**
  42784. * Gets wether tonemapping is enabled or not.
  42785. */
  42786. get: function () {
  42787. return this._imageProcessingConfiguration.toneMappingEnabled;
  42788. },
  42789. /**
  42790. * Sets wether tonemapping is enabled or not
  42791. */
  42792. set: function (value) {
  42793. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42794. },
  42795. enumerable: true,
  42796. configurable: true
  42797. });
  42798. ;
  42799. ;
  42800. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42801. /**
  42802. * The camera exposure used on this material.
  42803. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42804. * This corresponds to a photographic exposure.
  42805. */
  42806. get: function () {
  42807. return this._imageProcessingConfiguration.exposure;
  42808. },
  42809. /**
  42810. * The camera exposure used on this material.
  42811. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42812. * This corresponds to a photographic exposure.
  42813. */
  42814. set: function (value) {
  42815. this._imageProcessingConfiguration.exposure = value;
  42816. },
  42817. enumerable: true,
  42818. configurable: true
  42819. });
  42820. ;
  42821. ;
  42822. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42823. /**
  42824. * Gets The camera contrast used on this material.
  42825. */
  42826. get: function () {
  42827. return this._imageProcessingConfiguration.contrast;
  42828. },
  42829. /**
  42830. * Sets The camera contrast used on this material.
  42831. */
  42832. set: function (value) {
  42833. this._imageProcessingConfiguration.contrast = value;
  42834. },
  42835. enumerable: true,
  42836. configurable: true
  42837. });
  42838. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42839. /**
  42840. * Gets the Color Grading 2D Lookup Texture.
  42841. */
  42842. get: function () {
  42843. return this._imageProcessingConfiguration.colorGradingTexture;
  42844. },
  42845. /**
  42846. * Sets the Color Grading 2D Lookup Texture.
  42847. */
  42848. set: function (value) {
  42849. this._imageProcessingConfiguration.colorGradingTexture = value;
  42850. },
  42851. enumerable: true,
  42852. configurable: true
  42853. });
  42854. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42855. /**
  42856. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42857. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42858. * 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;
  42859. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42860. */
  42861. get: function () {
  42862. return this._imageProcessingConfiguration.colorCurves;
  42863. },
  42864. /**
  42865. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42866. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42867. * 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;
  42868. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42869. */
  42870. set: function (value) {
  42871. this._imageProcessingConfiguration.colorCurves = value;
  42872. },
  42873. enumerable: true,
  42874. configurable: true
  42875. });
  42876. /**
  42877. * Returns the name of this material class.
  42878. */
  42879. PBRMaterial.prototype.getClassName = function () {
  42880. return "PBRMaterial";
  42881. };
  42882. /**
  42883. * Returns an array of the actively used textures.
  42884. * @returns - Array of BaseTextures
  42885. */
  42886. PBRMaterial.prototype.getActiveTextures = function () {
  42887. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42888. if (this._albedoTexture) {
  42889. activeTextures.push(this._albedoTexture);
  42890. }
  42891. if (this._ambientTexture) {
  42892. activeTextures.push(this._ambientTexture);
  42893. }
  42894. if (this._opacityTexture) {
  42895. activeTextures.push(this._opacityTexture);
  42896. }
  42897. if (this._reflectionTexture) {
  42898. activeTextures.push(this._reflectionTexture);
  42899. }
  42900. if (this._emissiveTexture) {
  42901. activeTextures.push(this._emissiveTexture);
  42902. }
  42903. if (this._reflectivityTexture) {
  42904. activeTextures.push(this._reflectivityTexture);
  42905. }
  42906. if (this._metallicTexture) {
  42907. activeTextures.push(this._metallicTexture);
  42908. }
  42909. if (this._microSurfaceTexture) {
  42910. activeTextures.push(this._microSurfaceTexture);
  42911. }
  42912. if (this._bumpTexture) {
  42913. activeTextures.push(this._bumpTexture);
  42914. }
  42915. if (this._lightmapTexture) {
  42916. activeTextures.push(this._lightmapTexture);
  42917. }
  42918. if (this._refractionTexture) {
  42919. activeTextures.push(this._refractionTexture);
  42920. }
  42921. return activeTextures;
  42922. };
  42923. /**
  42924. * Checks to see if a texture is used in the material.
  42925. * @param texture - Base texture to use.
  42926. * @returns - Boolean specifying if a texture is used in the material.
  42927. */
  42928. PBRMaterial.prototype.hasTexture = function (texture) {
  42929. if (_super.prototype.hasTexture.call(this, texture)) {
  42930. return true;
  42931. }
  42932. if (this._albedoTexture === texture) {
  42933. return true;
  42934. }
  42935. if (this._ambientTexture === texture) {
  42936. return true;
  42937. }
  42938. if (this._opacityTexture === texture) {
  42939. return true;
  42940. }
  42941. if (this._reflectionTexture === texture) {
  42942. return true;
  42943. }
  42944. if (this._reflectivityTexture === texture) {
  42945. return true;
  42946. }
  42947. if (this._metallicTexture === texture) {
  42948. return true;
  42949. }
  42950. if (this._microSurfaceTexture === texture) {
  42951. return true;
  42952. }
  42953. if (this._bumpTexture === texture) {
  42954. return true;
  42955. }
  42956. if (this._lightmapTexture === texture) {
  42957. return true;
  42958. }
  42959. if (this._refractionTexture === texture) {
  42960. return true;
  42961. }
  42962. return false;
  42963. };
  42964. /**
  42965. * Makes a duplicate of the current material.
  42966. * @param name - name to use for the new material.
  42967. */
  42968. PBRMaterial.prototype.clone = function (name) {
  42969. var _this = this;
  42970. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42971. clone.id = name;
  42972. clone.name = name;
  42973. return clone;
  42974. };
  42975. /**
  42976. * Serializes this PBR Material.
  42977. * @returns - An object with the serialized material.
  42978. */
  42979. PBRMaterial.prototype.serialize = function () {
  42980. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42981. serializationObject.customType = "BABYLON.PBRMaterial";
  42982. return serializationObject;
  42983. };
  42984. // Statics
  42985. /**
  42986. * Parses a PBR Material from a serialized object.
  42987. * @param source - Serialized object.
  42988. * @param scene - BJS scene instance.
  42989. * @param rootUrl - url for the scene object
  42990. * @returns - PBRMaterial
  42991. */
  42992. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42993. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42994. };
  42995. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42996. /**
  42997. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42998. */
  42999. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  43000. /**
  43001. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43002. */
  43003. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  43004. /**
  43005. * 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.
  43006. * They are also discarded below the alpha cutoff threshold to improve performances.
  43007. */
  43008. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  43009. __decorate([
  43010. BABYLON.serialize(),
  43011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43012. ], PBRMaterial.prototype, "directIntensity", void 0);
  43013. __decorate([
  43014. BABYLON.serialize(),
  43015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43016. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  43017. __decorate([
  43018. BABYLON.serialize(),
  43019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43020. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  43021. __decorate([
  43022. BABYLON.serialize(),
  43023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43024. ], PBRMaterial.prototype, "specularIntensity", void 0);
  43025. __decorate([
  43026. BABYLON.serialize(),
  43027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43028. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43029. __decorate([
  43030. BABYLON.serializeAsTexture(),
  43031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43032. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43033. __decorate([
  43034. BABYLON.serializeAsTexture(),
  43035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43036. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43037. __decorate([
  43038. BABYLON.serialize(),
  43039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43040. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43041. __decorate([
  43042. BABYLON.serializeAsTexture(),
  43043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43044. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43045. __decorate([
  43046. BABYLON.serializeAsTexture(),
  43047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43048. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43049. __decorate([
  43050. BABYLON.serializeAsTexture(),
  43051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43052. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43053. __decorate([
  43054. BABYLON.serializeAsTexture(),
  43055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43056. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43057. __decorate([
  43058. BABYLON.serializeAsTexture(),
  43059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43060. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43061. __decorate([
  43062. BABYLON.serialize(),
  43063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43064. ], PBRMaterial.prototype, "metallic", void 0);
  43065. __decorate([
  43066. BABYLON.serialize(),
  43067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43068. ], PBRMaterial.prototype, "roughness", void 0);
  43069. __decorate([
  43070. BABYLON.serializeAsTexture(),
  43071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43072. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43073. __decorate([
  43074. BABYLON.serializeAsTexture(),
  43075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43076. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43077. __decorate([
  43078. BABYLON.serializeAsTexture(),
  43079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43080. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43081. __decorate([
  43082. BABYLON.serializeAsTexture(),
  43083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43084. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43085. __decorate([
  43086. BABYLON.serializeAsColor3("ambient"),
  43087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43088. ], PBRMaterial.prototype, "ambientColor", void 0);
  43089. __decorate([
  43090. BABYLON.serializeAsColor3("albedo"),
  43091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43092. ], PBRMaterial.prototype, "albedoColor", void 0);
  43093. __decorate([
  43094. BABYLON.serializeAsColor3("reflectivity"),
  43095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43096. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43097. __decorate([
  43098. BABYLON.serializeAsColor3("reflection"),
  43099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43100. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43101. __decorate([
  43102. BABYLON.serializeAsColor3("emissive"),
  43103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43104. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43105. __decorate([
  43106. BABYLON.serialize(),
  43107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43108. ], PBRMaterial.prototype, "microSurface", void 0);
  43109. __decorate([
  43110. BABYLON.serialize(),
  43111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43112. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43113. __decorate([
  43114. BABYLON.serialize(),
  43115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43116. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43117. __decorate([
  43118. BABYLON.serialize(),
  43119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43120. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43121. __decorate([
  43122. BABYLON.serialize(),
  43123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43124. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43125. __decorate([
  43126. BABYLON.serialize(),
  43127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43128. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43129. __decorate([
  43130. BABYLON.serialize(),
  43131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43132. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43133. __decorate([
  43134. BABYLON.serialize(),
  43135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43136. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43137. __decorate([
  43138. BABYLON.serialize(),
  43139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43140. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43141. __decorate([
  43142. BABYLON.serialize(),
  43143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43144. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43145. __decorate([
  43146. BABYLON.serialize(),
  43147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43148. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43149. __decorate([
  43150. BABYLON.serialize(),
  43151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43152. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43153. __decorate([
  43154. BABYLON.serialize(),
  43155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43156. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43157. __decorate([
  43158. BABYLON.serialize(),
  43159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43160. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43161. __decorate([
  43162. BABYLON.serialize(),
  43163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43164. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43165. __decorate([
  43166. BABYLON.serialize(),
  43167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43168. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43169. __decorate([
  43170. BABYLON.serialize(),
  43171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43172. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43173. __decorate([
  43174. BABYLON.serialize(),
  43175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43176. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43177. __decorate([
  43178. BABYLON.serialize(),
  43179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43180. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43181. __decorate([
  43182. BABYLON.serialize(),
  43183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43184. ], PBRMaterial.prototype, "useParallax", void 0);
  43185. __decorate([
  43186. BABYLON.serialize(),
  43187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43188. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43189. __decorate([
  43190. BABYLON.serialize(),
  43191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43192. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43193. __decorate([
  43194. BABYLON.serialize(),
  43195. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43196. ], PBRMaterial.prototype, "disableLighting", void 0);
  43197. __decorate([
  43198. BABYLON.serialize(),
  43199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43200. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43201. __decorate([
  43202. BABYLON.serialize(),
  43203. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43204. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43205. __decorate([
  43206. BABYLON.serialize(),
  43207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43208. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43209. __decorate([
  43210. BABYLON.serialize(),
  43211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43212. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43213. __decorate([
  43214. BABYLON.serialize(),
  43215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43216. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43217. __decorate([
  43218. BABYLON.serialize(),
  43219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43220. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43221. __decorate([
  43222. BABYLON.serialize(),
  43223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43224. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43225. __decorate([
  43226. BABYLON.serializeAsTexture(),
  43227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43228. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43229. __decorate([
  43230. BABYLON.serialize(),
  43231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43232. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43233. __decorate([
  43234. BABYLON.serialize(),
  43235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43236. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43237. __decorate([
  43238. BABYLON.serialize(),
  43239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43240. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43241. __decorate([
  43242. BABYLON.serialize(),
  43243. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43244. ], PBRMaterial.prototype, "unlit", void 0);
  43245. return PBRMaterial;
  43246. }(BABYLON.PBRBaseMaterial));
  43247. BABYLON.PBRMaterial = PBRMaterial;
  43248. })(BABYLON || (BABYLON = {}));
  43249. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43250. "use strict";
  43251. var BABYLON;
  43252. (function (BABYLON) {
  43253. /**
  43254. * The PBR material of BJS following the metal roughness convention.
  43255. *
  43256. * This fits to the PBR convention in the GLTF definition:
  43257. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43258. */
  43259. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43260. __extends(PBRMetallicRoughnessMaterial, _super);
  43261. /**
  43262. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43263. *
  43264. * @param name The material name
  43265. * @param scene The scene the material will be use in.
  43266. */
  43267. function PBRMetallicRoughnessMaterial(name, scene) {
  43268. var _this = _super.call(this, name, scene) || this;
  43269. _this._useRoughnessFromMetallicTextureAlpha = false;
  43270. _this._useRoughnessFromMetallicTextureGreen = true;
  43271. _this._useMetallnessFromMetallicTextureBlue = true;
  43272. _this.metallic = 1.0;
  43273. _this.roughness = 1.0;
  43274. return _this;
  43275. }
  43276. /**
  43277. * Return the currrent class name of the material.
  43278. */
  43279. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43280. return "PBRMetallicRoughnessMaterial";
  43281. };
  43282. /**
  43283. * Return the active textures of the material.
  43284. */
  43285. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43286. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43287. if (this.baseTexture) {
  43288. activeTextures.push(this.baseTexture);
  43289. }
  43290. if (this.metallicRoughnessTexture) {
  43291. activeTextures.push(this.metallicRoughnessTexture);
  43292. }
  43293. return activeTextures;
  43294. };
  43295. /**
  43296. * Checks to see if a texture is used in the material.
  43297. * @param texture - Base texture to use.
  43298. * @returns - Boolean specifying if a texture is used in the material.
  43299. */
  43300. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43301. if (_super.prototype.hasTexture.call(this, texture)) {
  43302. return true;
  43303. }
  43304. if (this.baseTexture === texture) {
  43305. return true;
  43306. }
  43307. if (this.metallicRoughnessTexture === texture) {
  43308. return true;
  43309. }
  43310. return false;
  43311. };
  43312. /**
  43313. * Makes a duplicate of the current material.
  43314. * @param name - name to use for the new material.
  43315. */
  43316. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43317. var _this = this;
  43318. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43319. clone.id = name;
  43320. clone.name = name;
  43321. return clone;
  43322. };
  43323. /**
  43324. * Serialize the material to a parsable JSON object.
  43325. */
  43326. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43327. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43328. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43329. return serializationObject;
  43330. };
  43331. /**
  43332. * Parses a JSON object correponding to the serialize function.
  43333. */
  43334. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43335. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43336. };
  43337. __decorate([
  43338. BABYLON.serializeAsColor3(),
  43339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43340. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43341. __decorate([
  43342. BABYLON.serializeAsTexture(),
  43343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43344. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43345. __decorate([
  43346. BABYLON.serialize(),
  43347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43348. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43349. __decorate([
  43350. BABYLON.serialize(),
  43351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43352. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43353. __decorate([
  43354. BABYLON.serializeAsTexture(),
  43355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43356. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43357. return PBRMetallicRoughnessMaterial;
  43358. }(BABYLON.PBRBaseSimpleMaterial));
  43359. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43360. })(BABYLON || (BABYLON = {}));
  43361. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43362. "use strict";
  43363. var BABYLON;
  43364. (function (BABYLON) {
  43365. /**
  43366. * The PBR material of BJS following the specular glossiness convention.
  43367. *
  43368. * This fits to the PBR convention in the GLTF definition:
  43369. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43370. */
  43371. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43372. __extends(PBRSpecularGlossinessMaterial, _super);
  43373. /**
  43374. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43375. *
  43376. * @param name The material name
  43377. * @param scene The scene the material will be use in.
  43378. */
  43379. function PBRSpecularGlossinessMaterial(name, scene) {
  43380. var _this = _super.call(this, name, scene) || this;
  43381. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43382. return _this;
  43383. }
  43384. /**
  43385. * Return the currrent class name of the material.
  43386. */
  43387. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43388. return "PBRSpecularGlossinessMaterial";
  43389. };
  43390. /**
  43391. * Return the active textures of the material.
  43392. */
  43393. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43394. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43395. if (this.diffuseTexture) {
  43396. activeTextures.push(this.diffuseTexture);
  43397. }
  43398. if (this.specularGlossinessTexture) {
  43399. activeTextures.push(this.specularGlossinessTexture);
  43400. }
  43401. return activeTextures;
  43402. };
  43403. /**
  43404. * Checks to see if a texture is used in the material.
  43405. * @param texture - Base texture to use.
  43406. * @returns - Boolean specifying if a texture is used in the material.
  43407. */
  43408. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43409. if (_super.prototype.hasTexture.call(this, texture)) {
  43410. return true;
  43411. }
  43412. if (this.diffuseTexture === texture) {
  43413. return true;
  43414. }
  43415. if (this.specularGlossinessTexture === texture) {
  43416. return true;
  43417. }
  43418. return false;
  43419. };
  43420. /**
  43421. * Makes a duplicate of the current material.
  43422. * @param name - name to use for the new material.
  43423. */
  43424. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43425. var _this = this;
  43426. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43427. clone.id = name;
  43428. clone.name = name;
  43429. return clone;
  43430. };
  43431. /**
  43432. * Serialize the material to a parsable JSON object.
  43433. */
  43434. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43435. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43436. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43437. return serializationObject;
  43438. };
  43439. /**
  43440. * Parses a JSON object correponding to the serialize function.
  43441. */
  43442. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43443. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43444. };
  43445. __decorate([
  43446. BABYLON.serializeAsColor3("diffuse"),
  43447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43448. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43449. __decorate([
  43450. BABYLON.serializeAsTexture(),
  43451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43452. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43453. __decorate([
  43454. BABYLON.serializeAsColor3("specular"),
  43455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43456. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43457. __decorate([
  43458. BABYLON.serialize(),
  43459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43460. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43461. __decorate([
  43462. BABYLON.serializeAsTexture(),
  43463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43464. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43465. return PBRSpecularGlossinessMaterial;
  43466. }(BABYLON.PBRBaseSimpleMaterial));
  43467. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43468. })(BABYLON || (BABYLON = {}));
  43469. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43470. "use strict";
  43471. var BABYLON;
  43472. (function (BABYLON) {
  43473. BABYLON.CameraInputTypes = {};
  43474. var CameraInputsManager = /** @class */ (function () {
  43475. function CameraInputsManager(camera) {
  43476. this.attached = {};
  43477. this.camera = camera;
  43478. this.checkInputs = function () { };
  43479. }
  43480. /**
  43481. * Add an input method to a camera.
  43482. * builtin inputs example: camera.inputs.addGamepad();
  43483. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43484. * @param input camera input method
  43485. */
  43486. CameraInputsManager.prototype.add = function (input) {
  43487. var type = input.getSimpleName();
  43488. if (this.attached[type]) {
  43489. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43490. return;
  43491. }
  43492. this.attached[type] = input;
  43493. input.camera = this.camera;
  43494. //for checkInputs, we are dynamically creating a function
  43495. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43496. if (input.checkInputs) {
  43497. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43498. }
  43499. if (this.attachedElement) {
  43500. input.attachControl(this.attachedElement);
  43501. }
  43502. };
  43503. /**
  43504. * Remove a specific input method from a camera
  43505. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43506. * @param inputToRemove camera input method
  43507. */
  43508. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43509. for (var cam in this.attached) {
  43510. var input = this.attached[cam];
  43511. if (input === inputToRemove) {
  43512. input.detachControl(this.attachedElement);
  43513. input.camera = null;
  43514. delete this.attached[cam];
  43515. this.rebuildInputCheck();
  43516. }
  43517. }
  43518. };
  43519. CameraInputsManager.prototype.removeByType = function (inputType) {
  43520. for (var cam in this.attached) {
  43521. var input = this.attached[cam];
  43522. if (input.getClassName() === inputType) {
  43523. input.detachControl(this.attachedElement);
  43524. input.camera = null;
  43525. delete this.attached[cam];
  43526. this.rebuildInputCheck();
  43527. }
  43528. }
  43529. };
  43530. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43531. var current = this.checkInputs;
  43532. return function () {
  43533. current();
  43534. fn();
  43535. };
  43536. };
  43537. CameraInputsManager.prototype.attachInput = function (input) {
  43538. if (this.attachedElement) {
  43539. input.attachControl(this.attachedElement, this.noPreventDefault);
  43540. }
  43541. };
  43542. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43543. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43544. if (this.attachedElement) {
  43545. return;
  43546. }
  43547. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43548. this.attachedElement = element;
  43549. this.noPreventDefault = noPreventDefault;
  43550. for (var cam in this.attached) {
  43551. this.attached[cam].attachControl(element, noPreventDefault);
  43552. }
  43553. };
  43554. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43555. if (disconnect === void 0) { disconnect = false; }
  43556. if (this.attachedElement !== element) {
  43557. return;
  43558. }
  43559. for (var cam in this.attached) {
  43560. this.attached[cam].detachControl(element);
  43561. if (disconnect) {
  43562. this.attached[cam].camera = null;
  43563. }
  43564. }
  43565. this.attachedElement = null;
  43566. };
  43567. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43568. this.checkInputs = function () { };
  43569. for (var cam in this.attached) {
  43570. var input = this.attached[cam];
  43571. if (input.checkInputs) {
  43572. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43573. }
  43574. }
  43575. };
  43576. /**
  43577. * Remove all attached input methods from a camera
  43578. */
  43579. CameraInputsManager.prototype.clear = function () {
  43580. if (this.attachedElement) {
  43581. this.detachElement(this.attachedElement, true);
  43582. }
  43583. this.attached = {};
  43584. this.attachedElement = null;
  43585. this.checkInputs = function () { };
  43586. };
  43587. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43588. var inputs = {};
  43589. for (var cam in this.attached) {
  43590. var input = this.attached[cam];
  43591. var res = BABYLON.SerializationHelper.Serialize(input);
  43592. inputs[input.getClassName()] = res;
  43593. }
  43594. serializedCamera.inputsmgr = inputs;
  43595. };
  43596. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43597. var parsedInputs = parsedCamera.inputsmgr;
  43598. if (parsedInputs) {
  43599. this.clear();
  43600. for (var n in parsedInputs) {
  43601. var construct = BABYLON.CameraInputTypes[n];
  43602. if (construct) {
  43603. var parsedinput = parsedInputs[n];
  43604. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43605. this.add(input);
  43606. }
  43607. }
  43608. }
  43609. else {
  43610. //2016-03-08 this part is for managing backward compatibility
  43611. for (var n in this.attached) {
  43612. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43613. if (construct) {
  43614. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43615. this.remove(this.attached[n]);
  43616. this.add(input);
  43617. }
  43618. }
  43619. }
  43620. };
  43621. return CameraInputsManager;
  43622. }());
  43623. BABYLON.CameraInputsManager = CameraInputsManager;
  43624. })(BABYLON || (BABYLON = {}));
  43625. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43626. "use strict";
  43627. var BABYLON;
  43628. (function (BABYLON) {
  43629. var TargetCamera = /** @class */ (function (_super) {
  43630. __extends(TargetCamera, _super);
  43631. function TargetCamera(name, position, scene) {
  43632. var _this = _super.call(this, name, position, scene) || this;
  43633. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43634. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43635. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43636. _this.speed = 2.0;
  43637. _this.noRotationConstraint = false;
  43638. _this.lockedTarget = null;
  43639. _this._currentTarget = BABYLON.Vector3.Zero();
  43640. _this._viewMatrix = BABYLON.Matrix.Zero();
  43641. _this._camMatrix = BABYLON.Matrix.Zero();
  43642. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43643. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43644. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43645. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43646. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43647. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43648. _this._tempMatrix = BABYLON.Matrix.Zero();
  43649. return _this;
  43650. }
  43651. TargetCamera.prototype.getFrontPosition = function (distance) {
  43652. this.getWorldMatrix();
  43653. var direction = this.getTarget().subtract(this.position);
  43654. direction.normalize();
  43655. direction.scaleInPlace(distance);
  43656. return this.globalPosition.add(direction);
  43657. };
  43658. TargetCamera.prototype._getLockedTargetPosition = function () {
  43659. if (!this.lockedTarget) {
  43660. return null;
  43661. }
  43662. if (this.lockedTarget.absolutePosition) {
  43663. this.lockedTarget.computeWorldMatrix();
  43664. }
  43665. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43666. };
  43667. TargetCamera.prototype.storeState = function () {
  43668. this._storedPosition = this.position.clone();
  43669. this._storedRotation = this.rotation.clone();
  43670. if (this.rotationQuaternion) {
  43671. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43672. }
  43673. return _super.prototype.storeState.call(this);
  43674. };
  43675. /**
  43676. * Restored camera state. You must call storeState() first
  43677. */
  43678. TargetCamera.prototype._restoreStateValues = function () {
  43679. if (!_super.prototype._restoreStateValues.call(this)) {
  43680. return false;
  43681. }
  43682. this.position = this._storedPosition.clone();
  43683. this.rotation = this._storedRotation.clone();
  43684. if (this.rotationQuaternion) {
  43685. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43686. }
  43687. this.cameraDirection.copyFromFloats(0, 0, 0);
  43688. this.cameraRotation.copyFromFloats(0, 0);
  43689. return true;
  43690. };
  43691. // Cache
  43692. TargetCamera.prototype._initCache = function () {
  43693. _super.prototype._initCache.call(this);
  43694. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43695. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43696. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43697. };
  43698. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43699. if (!ignoreParentClass) {
  43700. _super.prototype._updateCache.call(this);
  43701. }
  43702. var lockedTargetPosition = this._getLockedTargetPosition();
  43703. if (!lockedTargetPosition) {
  43704. this._cache.lockedTarget = null;
  43705. }
  43706. else {
  43707. if (!this._cache.lockedTarget) {
  43708. this._cache.lockedTarget = lockedTargetPosition.clone();
  43709. }
  43710. else {
  43711. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43712. }
  43713. }
  43714. this._cache.rotation.copyFrom(this.rotation);
  43715. if (this.rotationQuaternion)
  43716. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43717. };
  43718. // Synchronized
  43719. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43720. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43721. return false;
  43722. }
  43723. var lockedTargetPosition = this._getLockedTargetPosition();
  43724. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43725. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43726. };
  43727. // Methods
  43728. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43729. var engine = this.getEngine();
  43730. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43731. };
  43732. // Target
  43733. TargetCamera.prototype.setTarget = function (target) {
  43734. this.upVector.normalize();
  43735. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43736. this._camMatrix.invert();
  43737. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43738. var vDir = target.subtract(this.position);
  43739. if (vDir.x >= 0.0) {
  43740. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43741. }
  43742. else {
  43743. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43744. }
  43745. this.rotation.z = 0;
  43746. if (isNaN(this.rotation.x)) {
  43747. this.rotation.x = 0;
  43748. }
  43749. if (isNaN(this.rotation.y)) {
  43750. this.rotation.y = 0;
  43751. }
  43752. if (isNaN(this.rotation.z)) {
  43753. this.rotation.z = 0;
  43754. }
  43755. if (this.rotationQuaternion) {
  43756. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43757. }
  43758. };
  43759. /**
  43760. * Return the current target position of the camera. This value is expressed in local space.
  43761. */
  43762. TargetCamera.prototype.getTarget = function () {
  43763. return this._currentTarget;
  43764. };
  43765. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43766. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43767. };
  43768. TargetCamera.prototype._updatePosition = function () {
  43769. if (this.parent) {
  43770. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43771. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43772. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43773. return;
  43774. }
  43775. this.position.addInPlace(this.cameraDirection);
  43776. };
  43777. TargetCamera.prototype._checkInputs = function () {
  43778. var needToMove = this._decideIfNeedsToMove();
  43779. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43780. // Move
  43781. if (needToMove) {
  43782. this._updatePosition();
  43783. }
  43784. // Rotate
  43785. if (needToRotate) {
  43786. this.rotation.x += this.cameraRotation.x;
  43787. this.rotation.y += this.cameraRotation.y;
  43788. //rotate, if quaternion is set and rotation was used
  43789. if (this.rotationQuaternion) {
  43790. var len = this.rotation.lengthSquared();
  43791. if (len) {
  43792. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43793. }
  43794. }
  43795. if (!this.noRotationConstraint) {
  43796. var limit = (Math.PI / 2) * 0.95;
  43797. if (this.rotation.x > limit)
  43798. this.rotation.x = limit;
  43799. if (this.rotation.x < -limit)
  43800. this.rotation.x = -limit;
  43801. }
  43802. }
  43803. // Inertia
  43804. if (needToMove) {
  43805. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43806. this.cameraDirection.x = 0;
  43807. }
  43808. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43809. this.cameraDirection.y = 0;
  43810. }
  43811. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43812. this.cameraDirection.z = 0;
  43813. }
  43814. this.cameraDirection.scaleInPlace(this.inertia);
  43815. }
  43816. if (needToRotate) {
  43817. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43818. this.cameraRotation.x = 0;
  43819. }
  43820. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43821. this.cameraRotation.y = 0;
  43822. }
  43823. this.cameraRotation.scaleInPlace(this.inertia);
  43824. }
  43825. _super.prototype._checkInputs.call(this);
  43826. };
  43827. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43828. if (this.rotationQuaternion) {
  43829. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43830. }
  43831. else {
  43832. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43833. }
  43834. //update the up vector!
  43835. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43836. };
  43837. TargetCamera.prototype._getViewMatrix = function () {
  43838. if (this.lockedTarget) {
  43839. this.setTarget(this._getLockedTargetPosition());
  43840. }
  43841. // Compute
  43842. this._updateCameraRotationMatrix();
  43843. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43844. // Computing target and final matrix
  43845. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43846. if (this.getScene().useRightHandedSystem) {
  43847. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43848. }
  43849. else {
  43850. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43851. }
  43852. return this._viewMatrix;
  43853. };
  43854. /**
  43855. * @override
  43856. * Override Camera.createRigCamera
  43857. */
  43858. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43859. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43860. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43861. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43862. if (!this.rotationQuaternion) {
  43863. this.rotationQuaternion = new BABYLON.Quaternion();
  43864. }
  43865. rigCamera._cameraRigParams = {};
  43866. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43867. }
  43868. return rigCamera;
  43869. }
  43870. return null;
  43871. };
  43872. /**
  43873. * @override
  43874. * Override Camera._updateRigCameras
  43875. */
  43876. TargetCamera.prototype._updateRigCameras = function () {
  43877. var camLeft = this._rigCameras[0];
  43878. var camRight = this._rigCameras[1];
  43879. switch (this.cameraRigMode) {
  43880. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43881. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43882. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43883. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43884. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43885. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43886. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43887. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43888. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43889. camLeft.setTarget(this.getTarget());
  43890. camRight.setTarget(this.getTarget());
  43891. break;
  43892. case BABYLON.Camera.RIG_MODE_VR:
  43893. if (camLeft.rotationQuaternion) {
  43894. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43895. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43896. }
  43897. else {
  43898. camLeft.rotation.copyFrom(this.rotation);
  43899. camRight.rotation.copyFrom(this.rotation);
  43900. }
  43901. camLeft.position.copyFrom(this.position);
  43902. camRight.position.copyFrom(this.position);
  43903. break;
  43904. }
  43905. _super.prototype._updateRigCameras.call(this);
  43906. };
  43907. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43908. if (!this._rigCamTransformMatrix) {
  43909. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43910. }
  43911. var target = this.getTarget();
  43912. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43913. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43914. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43915. };
  43916. TargetCamera.prototype.getClassName = function () {
  43917. return "TargetCamera";
  43918. };
  43919. __decorate([
  43920. BABYLON.serializeAsVector3()
  43921. ], TargetCamera.prototype, "rotation", void 0);
  43922. __decorate([
  43923. BABYLON.serialize()
  43924. ], TargetCamera.prototype, "speed", void 0);
  43925. __decorate([
  43926. BABYLON.serializeAsMeshReference("lockedTargetId")
  43927. ], TargetCamera.prototype, "lockedTarget", void 0);
  43928. return TargetCamera;
  43929. }(BABYLON.Camera));
  43930. BABYLON.TargetCamera = TargetCamera;
  43931. })(BABYLON || (BABYLON = {}));
  43932. //# sourceMappingURL=babylon.targetCamera.js.map
  43933. "use strict";
  43934. var BABYLON;
  43935. (function (BABYLON) {
  43936. var FreeCameraMouseInput = /** @class */ (function () {
  43937. function FreeCameraMouseInput(touchEnabled) {
  43938. if (touchEnabled === void 0) { touchEnabled = true; }
  43939. this.touchEnabled = touchEnabled;
  43940. this.buttons = [0, 1, 2];
  43941. this.angularSensibility = 2000.0;
  43942. this.previousPosition = null;
  43943. }
  43944. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43945. var _this = this;
  43946. var engine = this.camera.getEngine();
  43947. if (!this._pointerInput) {
  43948. this._pointerInput = function (p, s) {
  43949. var evt = p.event;
  43950. if (engine.isInVRExclusivePointerMode) {
  43951. return;
  43952. }
  43953. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43954. return;
  43955. }
  43956. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43957. return;
  43958. }
  43959. var srcElement = (evt.srcElement || evt.target);
  43960. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43961. try {
  43962. srcElement.setPointerCapture(evt.pointerId);
  43963. }
  43964. catch (e) {
  43965. //Nothing to do with the error. Execution will continue.
  43966. }
  43967. _this.previousPosition = {
  43968. x: evt.clientX,
  43969. y: evt.clientY
  43970. };
  43971. if (!noPreventDefault) {
  43972. evt.preventDefault();
  43973. element.focus();
  43974. }
  43975. }
  43976. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43977. try {
  43978. srcElement.releasePointerCapture(evt.pointerId);
  43979. }
  43980. catch (e) {
  43981. //Nothing to do with the error.
  43982. }
  43983. _this.previousPosition = null;
  43984. if (!noPreventDefault) {
  43985. evt.preventDefault();
  43986. }
  43987. }
  43988. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43989. if (!_this.previousPosition || engine.isPointerLock) {
  43990. return;
  43991. }
  43992. var offsetX = evt.clientX - _this.previousPosition.x;
  43993. var offsetY = evt.clientY - _this.previousPosition.y;
  43994. if (_this.camera.getScene().useRightHandedSystem) {
  43995. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43996. }
  43997. else {
  43998. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43999. }
  44000. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44001. _this.previousPosition = {
  44002. x: evt.clientX,
  44003. y: evt.clientY
  44004. };
  44005. if (!noPreventDefault) {
  44006. evt.preventDefault();
  44007. }
  44008. }
  44009. };
  44010. }
  44011. this._onMouseMove = function (evt) {
  44012. if (!engine.isPointerLock) {
  44013. return;
  44014. }
  44015. if (engine.isInVRExclusivePointerMode) {
  44016. return;
  44017. }
  44018. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44019. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44020. if (_this.camera.getScene().useRightHandedSystem) {
  44021. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44022. }
  44023. else {
  44024. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44025. }
  44026. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44027. _this.previousPosition = null;
  44028. if (!noPreventDefault) {
  44029. evt.preventDefault();
  44030. }
  44031. };
  44032. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44033. element.addEventListener("mousemove", this._onMouseMove, false);
  44034. };
  44035. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44036. if (this._observer && element) {
  44037. this.camera.getScene().onPointerObservable.remove(this._observer);
  44038. if (this._onMouseMove) {
  44039. element.removeEventListener("mousemove", this._onMouseMove);
  44040. }
  44041. this._observer = null;
  44042. this._onMouseMove = null;
  44043. this.previousPosition = null;
  44044. }
  44045. };
  44046. FreeCameraMouseInput.prototype.getClassName = function () {
  44047. return "FreeCameraMouseInput";
  44048. };
  44049. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44050. return "mouse";
  44051. };
  44052. __decorate([
  44053. BABYLON.serialize()
  44054. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44055. __decorate([
  44056. BABYLON.serialize()
  44057. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44058. return FreeCameraMouseInput;
  44059. }());
  44060. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44061. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44062. })(BABYLON || (BABYLON = {}));
  44063. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44064. "use strict";
  44065. var BABYLON;
  44066. (function (BABYLON) {
  44067. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44068. function FreeCameraKeyboardMoveInput() {
  44069. this._keys = new Array();
  44070. this.keysUp = [38];
  44071. this.keysDown = [40];
  44072. this.keysLeft = [37];
  44073. this.keysRight = [39];
  44074. }
  44075. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44076. var _this = this;
  44077. if (this._onCanvasBlurObserver) {
  44078. return;
  44079. }
  44080. this._scene = this.camera.getScene();
  44081. this._engine = this._scene.getEngine();
  44082. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44083. _this._keys = [];
  44084. });
  44085. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44086. var evt = info.event;
  44087. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44088. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44089. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44090. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44091. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44092. var index = _this._keys.indexOf(evt.keyCode);
  44093. if (index === -1) {
  44094. _this._keys.push(evt.keyCode);
  44095. }
  44096. if (!noPreventDefault) {
  44097. evt.preventDefault();
  44098. }
  44099. }
  44100. }
  44101. else {
  44102. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44103. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44104. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44105. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44106. var index = _this._keys.indexOf(evt.keyCode);
  44107. if (index >= 0) {
  44108. _this._keys.splice(index, 1);
  44109. }
  44110. if (!noPreventDefault) {
  44111. evt.preventDefault();
  44112. }
  44113. }
  44114. }
  44115. });
  44116. };
  44117. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44118. if (this._scene) {
  44119. if (this._onKeyboardObserver) {
  44120. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44121. }
  44122. if (this._onCanvasBlurObserver) {
  44123. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44124. }
  44125. this._onKeyboardObserver = null;
  44126. this._onCanvasBlurObserver = null;
  44127. }
  44128. this._keys = [];
  44129. };
  44130. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44131. if (this._onKeyboardObserver) {
  44132. var camera = this.camera;
  44133. // Keyboard
  44134. for (var index = 0; index < this._keys.length; index++) {
  44135. var keyCode = this._keys[index];
  44136. var speed = camera._computeLocalCameraSpeed();
  44137. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44138. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44139. }
  44140. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44141. camera._localDirection.copyFromFloats(0, 0, speed);
  44142. }
  44143. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44144. camera._localDirection.copyFromFloats(speed, 0, 0);
  44145. }
  44146. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44147. camera._localDirection.copyFromFloats(0, 0, -speed);
  44148. }
  44149. if (camera.getScene().useRightHandedSystem) {
  44150. camera._localDirection.z *= -1;
  44151. }
  44152. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44153. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44154. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44155. }
  44156. }
  44157. };
  44158. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44159. return "FreeCameraKeyboardMoveInput";
  44160. };
  44161. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44162. this._keys = [];
  44163. };
  44164. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44165. return "keyboard";
  44166. };
  44167. __decorate([
  44168. BABYLON.serialize()
  44169. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44170. __decorate([
  44171. BABYLON.serialize()
  44172. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44173. __decorate([
  44174. BABYLON.serialize()
  44175. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44176. __decorate([
  44177. BABYLON.serialize()
  44178. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44179. return FreeCameraKeyboardMoveInput;
  44180. }());
  44181. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44182. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44183. })(BABYLON || (BABYLON = {}));
  44184. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44185. "use strict";
  44186. var BABYLON;
  44187. (function (BABYLON) {
  44188. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44189. __extends(FreeCameraInputsManager, _super);
  44190. function FreeCameraInputsManager(camera) {
  44191. return _super.call(this, camera) || this;
  44192. }
  44193. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44194. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44195. return this;
  44196. };
  44197. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44198. if (touchEnabled === void 0) { touchEnabled = true; }
  44199. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44200. return this;
  44201. };
  44202. FreeCameraInputsManager.prototype.addGamepad = function () {
  44203. this.add(new BABYLON.FreeCameraGamepadInput());
  44204. return this;
  44205. };
  44206. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44207. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44208. return this;
  44209. };
  44210. FreeCameraInputsManager.prototype.addTouch = function () {
  44211. this.add(new BABYLON.FreeCameraTouchInput());
  44212. return this;
  44213. };
  44214. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44215. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44216. return this;
  44217. };
  44218. return FreeCameraInputsManager;
  44219. }(BABYLON.CameraInputsManager));
  44220. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44221. })(BABYLON || (BABYLON = {}));
  44222. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44223. "use strict";
  44224. var BABYLON;
  44225. (function (BABYLON) {
  44226. var FreeCamera = /** @class */ (function (_super) {
  44227. __extends(FreeCamera, _super);
  44228. function FreeCamera(name, position, scene) {
  44229. var _this = _super.call(this, name, position, scene) || this;
  44230. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44231. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44232. _this.checkCollisions = false;
  44233. _this.applyGravity = false;
  44234. _this._needMoveForGravity = false;
  44235. _this._oldPosition = BABYLON.Vector3.Zero();
  44236. _this._diffPosition = BABYLON.Vector3.Zero();
  44237. _this._newPosition = BABYLON.Vector3.Zero();
  44238. // Collisions
  44239. _this._collisionMask = -1;
  44240. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44241. if (collidedMesh === void 0) { collidedMesh = null; }
  44242. //TODO move this to the collision coordinator!
  44243. if (_this.getScene().workerCollisions)
  44244. newPosition.multiplyInPlace(_this._collider._radius);
  44245. var updatePosition = function (newPos) {
  44246. _this._newPosition.copyFrom(newPos);
  44247. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44248. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44249. _this.position.addInPlace(_this._diffPosition);
  44250. if (_this.onCollide && collidedMesh) {
  44251. _this.onCollide(collidedMesh);
  44252. }
  44253. }
  44254. };
  44255. updatePosition(newPosition);
  44256. };
  44257. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44258. _this.inputs.addKeyboard().addMouse();
  44259. return _this;
  44260. }
  44261. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44262. //-- begin properties for backward compatibility for inputs
  44263. /**
  44264. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44265. * Higher values reduce sensitivity.
  44266. */
  44267. get: function () {
  44268. var mouse = this.inputs.attached["mouse"];
  44269. if (mouse)
  44270. return mouse.angularSensibility;
  44271. return 0;
  44272. },
  44273. /**
  44274. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44275. * Higher values reduce sensitivity.
  44276. */
  44277. set: function (value) {
  44278. var mouse = this.inputs.attached["mouse"];
  44279. if (mouse)
  44280. mouse.angularSensibility = value;
  44281. },
  44282. enumerable: true,
  44283. configurable: true
  44284. });
  44285. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44286. get: function () {
  44287. var keyboard = this.inputs.attached["keyboard"];
  44288. if (keyboard)
  44289. return keyboard.keysUp;
  44290. return [];
  44291. },
  44292. set: function (value) {
  44293. var keyboard = this.inputs.attached["keyboard"];
  44294. if (keyboard)
  44295. keyboard.keysUp = value;
  44296. },
  44297. enumerable: true,
  44298. configurable: true
  44299. });
  44300. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44301. get: function () {
  44302. var keyboard = this.inputs.attached["keyboard"];
  44303. if (keyboard)
  44304. return keyboard.keysDown;
  44305. return [];
  44306. },
  44307. set: function (value) {
  44308. var keyboard = this.inputs.attached["keyboard"];
  44309. if (keyboard)
  44310. keyboard.keysDown = value;
  44311. },
  44312. enumerable: true,
  44313. configurable: true
  44314. });
  44315. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44316. get: function () {
  44317. var keyboard = this.inputs.attached["keyboard"];
  44318. if (keyboard)
  44319. return keyboard.keysLeft;
  44320. return [];
  44321. },
  44322. set: function (value) {
  44323. var keyboard = this.inputs.attached["keyboard"];
  44324. if (keyboard)
  44325. keyboard.keysLeft = value;
  44326. },
  44327. enumerable: true,
  44328. configurable: true
  44329. });
  44330. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44331. get: function () {
  44332. var keyboard = this.inputs.attached["keyboard"];
  44333. if (keyboard)
  44334. return keyboard.keysRight;
  44335. return [];
  44336. },
  44337. set: function (value) {
  44338. var keyboard = this.inputs.attached["keyboard"];
  44339. if (keyboard)
  44340. keyboard.keysRight = value;
  44341. },
  44342. enumerable: true,
  44343. configurable: true
  44344. });
  44345. // Controls
  44346. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44347. this.inputs.attachElement(element, noPreventDefault);
  44348. };
  44349. FreeCamera.prototype.detachControl = function (element) {
  44350. this.inputs.detachElement(element);
  44351. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44352. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44353. };
  44354. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44355. get: function () {
  44356. return this._collisionMask;
  44357. },
  44358. set: function (mask) {
  44359. this._collisionMask = !isNaN(mask) ? mask : -1;
  44360. },
  44361. enumerable: true,
  44362. configurable: true
  44363. });
  44364. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44365. var globalPosition;
  44366. if (this.parent) {
  44367. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44368. }
  44369. else {
  44370. globalPosition = this.position;
  44371. }
  44372. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44373. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44374. if (!this._collider) {
  44375. this._collider = new BABYLON.Collider();
  44376. }
  44377. this._collider._radius = this.ellipsoid;
  44378. this._collider.collisionMask = this._collisionMask;
  44379. //no need for clone, as long as gravity is not on.
  44380. var actualDisplacement = displacement;
  44381. //add gravity to the direction to prevent the dual-collision checking
  44382. if (this.applyGravity) {
  44383. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44384. actualDisplacement = displacement.add(this.getScene().gravity);
  44385. }
  44386. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44387. };
  44388. FreeCamera.prototype._checkInputs = function () {
  44389. if (!this._localDirection) {
  44390. this._localDirection = BABYLON.Vector3.Zero();
  44391. this._transformedDirection = BABYLON.Vector3.Zero();
  44392. }
  44393. this.inputs.checkInputs();
  44394. _super.prototype._checkInputs.call(this);
  44395. };
  44396. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44397. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44398. };
  44399. FreeCamera.prototype._updatePosition = function () {
  44400. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44401. this._collideWithWorld(this.cameraDirection);
  44402. }
  44403. else {
  44404. _super.prototype._updatePosition.call(this);
  44405. }
  44406. };
  44407. FreeCamera.prototype.dispose = function () {
  44408. this.inputs.clear();
  44409. _super.prototype.dispose.call(this);
  44410. };
  44411. FreeCamera.prototype.getClassName = function () {
  44412. return "FreeCamera";
  44413. };
  44414. __decorate([
  44415. BABYLON.serializeAsVector3()
  44416. ], FreeCamera.prototype, "ellipsoid", void 0);
  44417. __decorate([
  44418. BABYLON.serializeAsVector3()
  44419. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44420. __decorate([
  44421. BABYLON.serialize()
  44422. ], FreeCamera.prototype, "checkCollisions", void 0);
  44423. __decorate([
  44424. BABYLON.serialize()
  44425. ], FreeCamera.prototype, "applyGravity", void 0);
  44426. return FreeCamera;
  44427. }(BABYLON.TargetCamera));
  44428. BABYLON.FreeCamera = FreeCamera;
  44429. })(BABYLON || (BABYLON = {}));
  44430. //# sourceMappingURL=babylon.freeCamera.js.map
  44431. "use strict";
  44432. var BABYLON;
  44433. (function (BABYLON) {
  44434. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44435. function ArcRotateCameraKeyboardMoveInput() {
  44436. this._keys = new Array();
  44437. this.keysUp = [38];
  44438. this.keysDown = [40];
  44439. this.keysLeft = [37];
  44440. this.keysRight = [39];
  44441. this.keysReset = [220];
  44442. this.panningSensibility = 50.0;
  44443. this.zoomingSensibility = 25.0;
  44444. this.useAltToZoom = true;
  44445. }
  44446. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44447. var _this = this;
  44448. if (this._onCanvasBlurObserver) {
  44449. return;
  44450. }
  44451. this._scene = this.camera.getScene();
  44452. this._engine = this._scene.getEngine();
  44453. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44454. _this._keys = [];
  44455. });
  44456. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44457. var evt = info.event;
  44458. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44459. _this._ctrlPressed = evt.ctrlKey;
  44460. _this._altPressed = evt.altKey;
  44461. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44462. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44463. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44464. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44465. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44466. var index = _this._keys.indexOf(evt.keyCode);
  44467. if (index === -1) {
  44468. _this._keys.push(evt.keyCode);
  44469. }
  44470. if (evt.preventDefault) {
  44471. if (!noPreventDefault) {
  44472. evt.preventDefault();
  44473. }
  44474. }
  44475. }
  44476. }
  44477. else {
  44478. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44479. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44480. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44481. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44482. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44483. var index = _this._keys.indexOf(evt.keyCode);
  44484. if (index >= 0) {
  44485. _this._keys.splice(index, 1);
  44486. }
  44487. if (evt.preventDefault) {
  44488. if (!noPreventDefault) {
  44489. evt.preventDefault();
  44490. }
  44491. }
  44492. }
  44493. }
  44494. });
  44495. };
  44496. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44497. if (this._scene) {
  44498. if (this._onKeyboardObserver) {
  44499. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44500. }
  44501. if (this._onCanvasBlurObserver) {
  44502. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44503. }
  44504. this._onKeyboardObserver = null;
  44505. this._onCanvasBlurObserver = null;
  44506. }
  44507. this._keys = [];
  44508. };
  44509. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44510. if (this._onKeyboardObserver) {
  44511. var camera = this.camera;
  44512. for (var index = 0; index < this._keys.length; index++) {
  44513. var keyCode = this._keys[index];
  44514. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44515. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44516. camera.inertialPanningX -= 1 / this.panningSensibility;
  44517. }
  44518. else {
  44519. camera.inertialAlphaOffset -= 0.01;
  44520. }
  44521. }
  44522. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44523. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44524. camera.inertialPanningY += 1 / this.panningSensibility;
  44525. }
  44526. else if (this._altPressed && this.useAltToZoom) {
  44527. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44528. }
  44529. else {
  44530. camera.inertialBetaOffset -= 0.01;
  44531. }
  44532. }
  44533. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44534. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44535. camera.inertialPanningX += 1 / this.panningSensibility;
  44536. }
  44537. else {
  44538. camera.inertialAlphaOffset += 0.01;
  44539. }
  44540. }
  44541. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44542. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44543. camera.inertialPanningY -= 1 / this.panningSensibility;
  44544. }
  44545. else if (this._altPressed && this.useAltToZoom) {
  44546. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44547. }
  44548. else {
  44549. camera.inertialBetaOffset += 0.01;
  44550. }
  44551. }
  44552. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44553. camera.restoreState();
  44554. }
  44555. }
  44556. }
  44557. };
  44558. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44559. return "ArcRotateCameraKeyboardMoveInput";
  44560. };
  44561. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44562. return "keyboard";
  44563. };
  44564. __decorate([
  44565. BABYLON.serialize()
  44566. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44567. __decorate([
  44568. BABYLON.serialize()
  44569. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44570. __decorate([
  44571. BABYLON.serialize()
  44572. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44573. __decorate([
  44574. BABYLON.serialize()
  44575. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44576. __decorate([
  44577. BABYLON.serialize()
  44578. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44579. __decorate([
  44580. BABYLON.serialize()
  44581. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44582. __decorate([
  44583. BABYLON.serialize()
  44584. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44585. __decorate([
  44586. BABYLON.serialize()
  44587. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44588. return ArcRotateCameraKeyboardMoveInput;
  44589. }());
  44590. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44591. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44592. })(BABYLON || (BABYLON = {}));
  44593. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44594. "use strict";
  44595. var BABYLON;
  44596. (function (BABYLON) {
  44597. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44598. function ArcRotateCameraMouseWheelInput() {
  44599. this.wheelPrecision = 3.0;
  44600. /**
  44601. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44602. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44603. */
  44604. this.wheelDeltaPercentage = 0;
  44605. }
  44606. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44607. var _this = this;
  44608. this._wheel = function (p, s) {
  44609. //sanity check - this should be a PointerWheel event.
  44610. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44611. return;
  44612. var event = p.event;
  44613. var delta = 0;
  44614. if (event.wheelDelta) {
  44615. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44616. }
  44617. else if (event.detail) {
  44618. delta = -event.detail / _this.wheelPrecision;
  44619. }
  44620. if (delta)
  44621. _this.camera.inertialRadiusOffset += delta;
  44622. if (event.preventDefault) {
  44623. if (!noPreventDefault) {
  44624. event.preventDefault();
  44625. }
  44626. }
  44627. };
  44628. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44629. };
  44630. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44631. if (this._observer && element) {
  44632. this.camera.getScene().onPointerObservable.remove(this._observer);
  44633. this._observer = null;
  44634. this._wheel = null;
  44635. }
  44636. };
  44637. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44638. return "ArcRotateCameraMouseWheelInput";
  44639. };
  44640. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44641. return "mousewheel";
  44642. };
  44643. __decorate([
  44644. BABYLON.serialize()
  44645. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44646. __decorate([
  44647. BABYLON.serialize()
  44648. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44649. return ArcRotateCameraMouseWheelInput;
  44650. }());
  44651. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44652. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44653. })(BABYLON || (BABYLON = {}));
  44654. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44655. "use strict";
  44656. var BABYLON;
  44657. (function (BABYLON) {
  44658. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44659. function ArcRotateCameraPointersInput() {
  44660. this.buttons = [0, 1, 2];
  44661. this.angularSensibilityX = 1000.0;
  44662. this.angularSensibilityY = 1000.0;
  44663. this.pinchPrecision = 12.0;
  44664. /**
  44665. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44666. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44667. */
  44668. this.pinchDeltaPercentage = 0;
  44669. this.panningSensibility = 1000.0;
  44670. this.multiTouchPanning = true;
  44671. this.multiTouchPanAndZoom = true;
  44672. this._isPanClick = false;
  44673. this.pinchInwards = true;
  44674. }
  44675. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44676. var _this = this;
  44677. var engine = this.camera.getEngine();
  44678. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44679. var pointA = null;
  44680. var pointB = null;
  44681. var previousPinchSquaredDistance = 0;
  44682. var initialDistance = 0;
  44683. var twoFingerActivityCount = 0;
  44684. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44685. this._pointerInput = function (p, s) {
  44686. var evt = p.event;
  44687. var isTouch = p.event.pointerType === "touch";
  44688. if (engine.isInVRExclusivePointerMode) {
  44689. return;
  44690. }
  44691. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44692. return;
  44693. }
  44694. var srcElement = (evt.srcElement || evt.target);
  44695. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44696. try {
  44697. srcElement.setPointerCapture(evt.pointerId);
  44698. }
  44699. catch (e) {
  44700. //Nothing to do with the error. Execution will continue.
  44701. }
  44702. // Manage panning with pan button click
  44703. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44704. // manage pointers
  44705. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44706. if (pointA === null) {
  44707. pointA = cacheSoloPointer;
  44708. }
  44709. else if (pointB === null) {
  44710. pointB = cacheSoloPointer;
  44711. }
  44712. if (!noPreventDefault) {
  44713. evt.preventDefault();
  44714. element.focus();
  44715. }
  44716. }
  44717. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44718. _this.camera.restoreState();
  44719. }
  44720. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44721. try {
  44722. srcElement.releasePointerCapture(evt.pointerId);
  44723. }
  44724. catch (e) {
  44725. //Nothing to do with the error.
  44726. }
  44727. cacheSoloPointer = null;
  44728. previousPinchSquaredDistance = 0;
  44729. previousMultiTouchPanPosition.isPaning = false;
  44730. previousMultiTouchPanPosition.isPinching = false;
  44731. twoFingerActivityCount = 0;
  44732. initialDistance = 0;
  44733. if (!isTouch) {
  44734. pointB = null; // Mouse and pen are mono pointer
  44735. }
  44736. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44737. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44738. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44739. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44740. if (engine.badOS) {
  44741. pointA = pointB = null;
  44742. }
  44743. else {
  44744. //only remove the impacted pointer in case of multitouch allowing on most
  44745. //platforms switching from rotate to zoom and pan seamlessly.
  44746. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44747. pointA = pointB;
  44748. pointB = null;
  44749. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44750. }
  44751. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44752. pointB = null;
  44753. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44754. }
  44755. else {
  44756. pointA = pointB = null;
  44757. }
  44758. }
  44759. if (!noPreventDefault) {
  44760. evt.preventDefault();
  44761. }
  44762. }
  44763. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44764. if (!noPreventDefault) {
  44765. evt.preventDefault();
  44766. }
  44767. // One button down
  44768. if (pointA && pointB === null && cacheSoloPointer) {
  44769. if (_this.panningSensibility !== 0 &&
  44770. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44771. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44772. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44773. }
  44774. else {
  44775. var offsetX = evt.clientX - cacheSoloPointer.x;
  44776. var offsetY = evt.clientY - cacheSoloPointer.y;
  44777. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44778. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44779. }
  44780. cacheSoloPointer.x = evt.clientX;
  44781. cacheSoloPointer.y = evt.clientY;
  44782. }
  44783. else if (pointA && pointB) {
  44784. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44785. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44786. ed.x = evt.clientX;
  44787. ed.y = evt.clientY;
  44788. var direction = _this.pinchInwards ? 1 : -1;
  44789. var distX = pointA.x - pointB.x;
  44790. var distY = pointA.y - pointB.y;
  44791. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44792. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44793. if (previousPinchSquaredDistance === 0) {
  44794. initialDistance = pinchDistance;
  44795. previousPinchSquaredDistance = pinchSquaredDistance;
  44796. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44797. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44798. return;
  44799. }
  44800. if (_this.multiTouchPanAndZoom) {
  44801. if (_this.pinchDeltaPercentage) {
  44802. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44803. }
  44804. else {
  44805. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44806. (_this.pinchPrecision *
  44807. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44808. direction);
  44809. }
  44810. if (_this.panningSensibility !== 0) {
  44811. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44812. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44813. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44814. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44815. previousMultiTouchPanPosition.x = pointersCenterX;
  44816. previousMultiTouchPanPosition.y = pointersCenterY;
  44817. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44818. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44819. }
  44820. }
  44821. else {
  44822. twoFingerActivityCount++;
  44823. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44824. if (_this.pinchDeltaPercentage) {
  44825. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44826. }
  44827. else {
  44828. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44829. (_this.pinchPrecision *
  44830. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44831. direction);
  44832. }
  44833. previousMultiTouchPanPosition.isPaning = false;
  44834. previousMultiTouchPanPosition.isPinching = true;
  44835. }
  44836. else {
  44837. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44838. if (!previousMultiTouchPanPosition.isPaning) {
  44839. previousMultiTouchPanPosition.isPaning = true;
  44840. previousMultiTouchPanPosition.isPinching = false;
  44841. previousMultiTouchPanPosition.x = ed.x;
  44842. previousMultiTouchPanPosition.y = ed.y;
  44843. return;
  44844. }
  44845. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44846. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44847. }
  44848. }
  44849. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44850. previousMultiTouchPanPosition.x = ed.x;
  44851. previousMultiTouchPanPosition.y = ed.y;
  44852. }
  44853. }
  44854. previousPinchSquaredDistance = pinchSquaredDistance;
  44855. }
  44856. }
  44857. };
  44858. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44859. this._onContextMenu = function (evt) {
  44860. evt.preventDefault();
  44861. };
  44862. if (!this.camera._useCtrlForPanning) {
  44863. element.addEventListener("contextmenu", this._onContextMenu, false);
  44864. }
  44865. this._onLostFocus = function () {
  44866. //this._keys = [];
  44867. pointA = pointB = null;
  44868. previousPinchSquaredDistance = 0;
  44869. previousMultiTouchPanPosition.isPaning = false;
  44870. previousMultiTouchPanPosition.isPinching = false;
  44871. twoFingerActivityCount = 0;
  44872. cacheSoloPointer = null;
  44873. initialDistance = 0;
  44874. };
  44875. this._onMouseMove = function (evt) {
  44876. if (!engine.isPointerLock) {
  44877. return;
  44878. }
  44879. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44880. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44881. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44882. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44883. if (!noPreventDefault) {
  44884. evt.preventDefault();
  44885. }
  44886. };
  44887. this._onGestureStart = function (e) {
  44888. if (window.MSGesture === undefined) {
  44889. return;
  44890. }
  44891. if (!_this._MSGestureHandler) {
  44892. _this._MSGestureHandler = new MSGesture();
  44893. _this._MSGestureHandler.target = element;
  44894. }
  44895. _this._MSGestureHandler.addPointer(e.pointerId);
  44896. };
  44897. this._onGesture = function (e) {
  44898. _this.camera.radius *= e.scale;
  44899. if (e.preventDefault) {
  44900. if (!noPreventDefault) {
  44901. e.stopPropagation();
  44902. e.preventDefault();
  44903. }
  44904. }
  44905. };
  44906. element.addEventListener("mousemove", this._onMouseMove, false);
  44907. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44908. element.addEventListener("MSGestureChange", this._onGesture, false);
  44909. BABYLON.Tools.RegisterTopRootEvents([
  44910. { name: "blur", handler: this._onLostFocus }
  44911. ]);
  44912. };
  44913. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44914. if (this._onLostFocus) {
  44915. BABYLON.Tools.UnregisterTopRootEvents([
  44916. { name: "blur", handler: this._onLostFocus }
  44917. ]);
  44918. }
  44919. if (element && this._observer) {
  44920. this.camera.getScene().onPointerObservable.remove(this._observer);
  44921. this._observer = null;
  44922. if (this._onContextMenu) {
  44923. element.removeEventListener("contextmenu", this._onContextMenu);
  44924. }
  44925. if (this._onMouseMove) {
  44926. element.removeEventListener("mousemove", this._onMouseMove);
  44927. }
  44928. if (this._onGestureStart) {
  44929. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44930. }
  44931. if (this._onGesture) {
  44932. element.removeEventListener("MSGestureChange", this._onGesture);
  44933. }
  44934. this._isPanClick = false;
  44935. this.pinchInwards = true;
  44936. this._onMouseMove = null;
  44937. this._onGestureStart = null;
  44938. this._onGesture = null;
  44939. this._MSGestureHandler = null;
  44940. this._onLostFocus = null;
  44941. this._onContextMenu = null;
  44942. }
  44943. };
  44944. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44945. return "ArcRotateCameraPointersInput";
  44946. };
  44947. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44948. return "pointers";
  44949. };
  44950. __decorate([
  44951. BABYLON.serialize()
  44952. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44953. __decorate([
  44954. BABYLON.serialize()
  44955. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44956. __decorate([
  44957. BABYLON.serialize()
  44958. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44959. __decorate([
  44960. BABYLON.serialize()
  44961. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44962. __decorate([
  44963. BABYLON.serialize()
  44964. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44965. __decorate([
  44966. BABYLON.serialize()
  44967. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44968. __decorate([
  44969. BABYLON.serialize()
  44970. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44971. __decorate([
  44972. BABYLON.serialize()
  44973. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44974. return ArcRotateCameraPointersInput;
  44975. }());
  44976. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44977. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44978. })(BABYLON || (BABYLON = {}));
  44979. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44980. "use strict";
  44981. var BABYLON;
  44982. (function (BABYLON) {
  44983. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44984. __extends(ArcRotateCameraInputsManager, _super);
  44985. function ArcRotateCameraInputsManager(camera) {
  44986. return _super.call(this, camera) || this;
  44987. }
  44988. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44989. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44990. return this;
  44991. };
  44992. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44993. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44994. return this;
  44995. };
  44996. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44997. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44998. return this;
  44999. };
  45000. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  45001. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  45002. return this;
  45003. };
  45004. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  45005. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  45006. return this;
  45007. };
  45008. return ArcRotateCameraInputsManager;
  45009. }(BABYLON.CameraInputsManager));
  45010. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  45011. })(BABYLON || (BABYLON = {}));
  45012. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  45013. "use strict";
  45014. var BABYLON;
  45015. (function (BABYLON) {
  45016. var ArcRotateCamera = /** @class */ (function (_super) {
  45017. __extends(ArcRotateCamera, _super);
  45018. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45019. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45020. _this.inertialAlphaOffset = 0;
  45021. _this.inertialBetaOffset = 0;
  45022. _this.inertialRadiusOffset = 0;
  45023. _this.lowerAlphaLimit = null;
  45024. _this.upperAlphaLimit = null;
  45025. _this.lowerBetaLimit = 0.01;
  45026. _this.upperBetaLimit = Math.PI;
  45027. _this.lowerRadiusLimit = null;
  45028. _this.upperRadiusLimit = null;
  45029. _this.inertialPanningX = 0;
  45030. _this.inertialPanningY = 0;
  45031. _this.pinchToPanMaxDistance = 20;
  45032. _this.panningDistanceLimit = null;
  45033. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45034. _this.panningInertia = 0.9;
  45035. //-- end properties for backward compatibility for inputs
  45036. _this.zoomOnFactor = 1;
  45037. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45038. _this.allowUpsideDown = true;
  45039. _this._viewMatrix = new BABYLON.Matrix();
  45040. // Panning
  45041. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45042. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45043. _this.checkCollisions = false;
  45044. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45045. _this._previousPosition = BABYLON.Vector3.Zero();
  45046. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45047. _this._newPosition = BABYLON.Vector3.Zero();
  45048. _this._computationVector = BABYLON.Vector3.Zero();
  45049. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45050. if (collidedMesh === void 0) { collidedMesh = null; }
  45051. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45052. newPosition.multiplyInPlace(_this._collider._radius);
  45053. }
  45054. if (!collidedMesh) {
  45055. _this._previousPosition.copyFrom(_this.position);
  45056. }
  45057. else {
  45058. _this.setPosition(newPosition);
  45059. if (_this.onCollide) {
  45060. _this.onCollide(collidedMesh);
  45061. }
  45062. }
  45063. // Recompute because of constraints
  45064. var cosa = Math.cos(_this.alpha);
  45065. var sina = Math.sin(_this.alpha);
  45066. var cosb = Math.cos(_this.beta);
  45067. var sinb = Math.sin(_this.beta);
  45068. if (sinb === 0) {
  45069. sinb = 0.0001;
  45070. }
  45071. var target = _this._getTargetPosition();
  45072. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45073. target.addToRef(_this._computationVector, _this._newPosition);
  45074. _this.position.copyFrom(_this._newPosition);
  45075. var up = _this.upVector;
  45076. if (_this.allowUpsideDown && _this.beta < 0) {
  45077. up = up.clone();
  45078. up = up.negate();
  45079. }
  45080. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45081. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45082. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45083. _this._collisionTriggered = false;
  45084. };
  45085. _this._target = BABYLON.Vector3.Zero();
  45086. if (target) {
  45087. _this.setTarget(target);
  45088. }
  45089. _this.alpha = alpha;
  45090. _this.beta = beta;
  45091. _this.radius = radius;
  45092. _this.getViewMatrix();
  45093. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45094. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45095. return _this;
  45096. }
  45097. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45098. get: function () {
  45099. return this._target;
  45100. },
  45101. set: function (value) {
  45102. this.setTarget(value);
  45103. },
  45104. enumerable: true,
  45105. configurable: true
  45106. });
  45107. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45108. //-- begin properties for backward compatibility for inputs
  45109. get: function () {
  45110. var pointers = this.inputs.attached["pointers"];
  45111. if (pointers)
  45112. return pointers.angularSensibilityX;
  45113. return 0;
  45114. },
  45115. set: function (value) {
  45116. var pointers = this.inputs.attached["pointers"];
  45117. if (pointers) {
  45118. pointers.angularSensibilityX = value;
  45119. }
  45120. },
  45121. enumerable: true,
  45122. configurable: true
  45123. });
  45124. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45125. get: function () {
  45126. var pointers = this.inputs.attached["pointers"];
  45127. if (pointers)
  45128. return pointers.angularSensibilityY;
  45129. return 0;
  45130. },
  45131. set: function (value) {
  45132. var pointers = this.inputs.attached["pointers"];
  45133. if (pointers) {
  45134. pointers.angularSensibilityY = value;
  45135. }
  45136. },
  45137. enumerable: true,
  45138. configurable: true
  45139. });
  45140. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45141. get: function () {
  45142. var pointers = this.inputs.attached["pointers"];
  45143. if (pointers)
  45144. return pointers.pinchPrecision;
  45145. return 0;
  45146. },
  45147. set: function (value) {
  45148. var pointers = this.inputs.attached["pointers"];
  45149. if (pointers) {
  45150. pointers.pinchPrecision = value;
  45151. }
  45152. },
  45153. enumerable: true,
  45154. configurable: true
  45155. });
  45156. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45157. get: function () {
  45158. var pointers = this.inputs.attached["pointers"];
  45159. if (pointers)
  45160. return pointers.pinchDeltaPercentage;
  45161. return 0;
  45162. },
  45163. set: function (value) {
  45164. var pointers = this.inputs.attached["pointers"];
  45165. if (pointers) {
  45166. pointers.pinchDeltaPercentage = value;
  45167. }
  45168. },
  45169. enumerable: true,
  45170. configurable: true
  45171. });
  45172. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45173. get: function () {
  45174. var pointers = this.inputs.attached["pointers"];
  45175. if (pointers)
  45176. return pointers.panningSensibility;
  45177. return 0;
  45178. },
  45179. set: function (value) {
  45180. var pointers = this.inputs.attached["pointers"];
  45181. if (pointers) {
  45182. pointers.panningSensibility = value;
  45183. }
  45184. },
  45185. enumerable: true,
  45186. configurable: true
  45187. });
  45188. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45189. get: function () {
  45190. var keyboard = this.inputs.attached["keyboard"];
  45191. if (keyboard)
  45192. return keyboard.keysUp;
  45193. return [];
  45194. },
  45195. set: function (value) {
  45196. var keyboard = this.inputs.attached["keyboard"];
  45197. if (keyboard)
  45198. keyboard.keysUp = value;
  45199. },
  45200. enumerable: true,
  45201. configurable: true
  45202. });
  45203. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45204. get: function () {
  45205. var keyboard = this.inputs.attached["keyboard"];
  45206. if (keyboard)
  45207. return keyboard.keysDown;
  45208. return [];
  45209. },
  45210. set: function (value) {
  45211. var keyboard = this.inputs.attached["keyboard"];
  45212. if (keyboard)
  45213. keyboard.keysDown = value;
  45214. },
  45215. enumerable: true,
  45216. configurable: true
  45217. });
  45218. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45219. get: function () {
  45220. var keyboard = this.inputs.attached["keyboard"];
  45221. if (keyboard)
  45222. return keyboard.keysLeft;
  45223. return [];
  45224. },
  45225. set: function (value) {
  45226. var keyboard = this.inputs.attached["keyboard"];
  45227. if (keyboard)
  45228. keyboard.keysLeft = value;
  45229. },
  45230. enumerable: true,
  45231. configurable: true
  45232. });
  45233. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45234. get: function () {
  45235. var keyboard = this.inputs.attached["keyboard"];
  45236. if (keyboard)
  45237. return keyboard.keysRight;
  45238. return [];
  45239. },
  45240. set: function (value) {
  45241. var keyboard = this.inputs.attached["keyboard"];
  45242. if (keyboard)
  45243. keyboard.keysRight = value;
  45244. },
  45245. enumerable: true,
  45246. configurable: true
  45247. });
  45248. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45249. get: function () {
  45250. var mousewheel = this.inputs.attached["mousewheel"];
  45251. if (mousewheel)
  45252. return mousewheel.wheelPrecision;
  45253. return 0;
  45254. },
  45255. set: function (value) {
  45256. var mousewheel = this.inputs.attached["mousewheel"];
  45257. if (mousewheel)
  45258. mousewheel.wheelPrecision = value;
  45259. },
  45260. enumerable: true,
  45261. configurable: true
  45262. });
  45263. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45264. get: function () {
  45265. var mousewheel = this.inputs.attached["mousewheel"];
  45266. if (mousewheel)
  45267. return mousewheel.wheelDeltaPercentage;
  45268. return 0;
  45269. },
  45270. set: function (value) {
  45271. var mousewheel = this.inputs.attached["mousewheel"];
  45272. if (mousewheel)
  45273. mousewheel.wheelDeltaPercentage = value;
  45274. },
  45275. enumerable: true,
  45276. configurable: true
  45277. });
  45278. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45279. get: function () {
  45280. return this._bouncingBehavior;
  45281. },
  45282. enumerable: true,
  45283. configurable: true
  45284. });
  45285. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45286. get: function () {
  45287. return this._bouncingBehavior != null;
  45288. },
  45289. set: function (value) {
  45290. if (value === this.useBouncingBehavior) {
  45291. return;
  45292. }
  45293. if (value) {
  45294. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45295. this.addBehavior(this._bouncingBehavior);
  45296. }
  45297. else if (this._bouncingBehavior) {
  45298. this.removeBehavior(this._bouncingBehavior);
  45299. this._bouncingBehavior = null;
  45300. }
  45301. },
  45302. enumerable: true,
  45303. configurable: true
  45304. });
  45305. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45306. get: function () {
  45307. return this._framingBehavior;
  45308. },
  45309. enumerable: true,
  45310. configurable: true
  45311. });
  45312. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45313. get: function () {
  45314. return this._framingBehavior != null;
  45315. },
  45316. set: function (value) {
  45317. if (value === this.useFramingBehavior) {
  45318. return;
  45319. }
  45320. if (value) {
  45321. this._framingBehavior = new BABYLON.FramingBehavior();
  45322. this.addBehavior(this._framingBehavior);
  45323. }
  45324. else if (this._framingBehavior) {
  45325. this.removeBehavior(this._framingBehavior);
  45326. this._framingBehavior = null;
  45327. }
  45328. },
  45329. enumerable: true,
  45330. configurable: true
  45331. });
  45332. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45333. get: function () {
  45334. return this._autoRotationBehavior;
  45335. },
  45336. enumerable: true,
  45337. configurable: true
  45338. });
  45339. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45340. get: function () {
  45341. return this._autoRotationBehavior != null;
  45342. },
  45343. set: function (value) {
  45344. if (value === this.useAutoRotationBehavior) {
  45345. return;
  45346. }
  45347. if (value) {
  45348. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45349. this.addBehavior(this._autoRotationBehavior);
  45350. }
  45351. else if (this._autoRotationBehavior) {
  45352. this.removeBehavior(this._autoRotationBehavior);
  45353. this._autoRotationBehavior = null;
  45354. }
  45355. },
  45356. enumerable: true,
  45357. configurable: true
  45358. });
  45359. // Cache
  45360. ArcRotateCamera.prototype._initCache = function () {
  45361. _super.prototype._initCache.call(this);
  45362. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45363. this._cache.alpha = undefined;
  45364. this._cache.beta = undefined;
  45365. this._cache.radius = undefined;
  45366. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45367. };
  45368. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45369. if (!ignoreParentClass) {
  45370. _super.prototype._updateCache.call(this);
  45371. }
  45372. this._cache._target.copyFrom(this._getTargetPosition());
  45373. this._cache.alpha = this.alpha;
  45374. this._cache.beta = this.beta;
  45375. this._cache.radius = this.radius;
  45376. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45377. };
  45378. ArcRotateCamera.prototype._getTargetPosition = function () {
  45379. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45380. var pos = this._targetHost.getAbsolutePosition();
  45381. if (this._targetBoundingCenter) {
  45382. pos.addToRef(this._targetBoundingCenter, this._target);
  45383. }
  45384. else {
  45385. this._target.copyFrom(pos);
  45386. }
  45387. }
  45388. var lockedTargetPosition = this._getLockedTargetPosition();
  45389. if (lockedTargetPosition) {
  45390. return lockedTargetPosition;
  45391. }
  45392. return this._target;
  45393. };
  45394. ArcRotateCamera.prototype.storeState = function () {
  45395. this._storedAlpha = this.alpha;
  45396. this._storedBeta = this.beta;
  45397. this._storedRadius = this.radius;
  45398. this._storedTarget = this._getTargetPosition().clone();
  45399. return _super.prototype.storeState.call(this);
  45400. };
  45401. /**
  45402. * Restored camera state. You must call storeState() first
  45403. */
  45404. ArcRotateCamera.prototype._restoreStateValues = function () {
  45405. if (!_super.prototype._restoreStateValues.call(this)) {
  45406. return false;
  45407. }
  45408. this.alpha = this._storedAlpha;
  45409. this.beta = this._storedBeta;
  45410. this.radius = this._storedRadius;
  45411. this.setTarget(this._storedTarget.clone());
  45412. this.inertialAlphaOffset = 0;
  45413. this.inertialBetaOffset = 0;
  45414. this.inertialRadiusOffset = 0;
  45415. this.inertialPanningX = 0;
  45416. this.inertialPanningY = 0;
  45417. return true;
  45418. };
  45419. // Synchronized
  45420. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45421. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45422. return false;
  45423. return this._cache._target.equals(this._getTargetPosition())
  45424. && this._cache.alpha === this.alpha
  45425. && this._cache.beta === this.beta
  45426. && this._cache.radius === this.radius
  45427. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45428. };
  45429. // Methods
  45430. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45431. var _this = this;
  45432. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45433. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45434. this._useCtrlForPanning = useCtrlForPanning;
  45435. this._panningMouseButton = panningMouseButton;
  45436. this.inputs.attachElement(element, noPreventDefault);
  45437. this._reset = function () {
  45438. _this.inertialAlphaOffset = 0;
  45439. _this.inertialBetaOffset = 0;
  45440. _this.inertialRadiusOffset = 0;
  45441. _this.inertialPanningX = 0;
  45442. _this.inertialPanningY = 0;
  45443. };
  45444. };
  45445. ArcRotateCamera.prototype.detachControl = function (element) {
  45446. this.inputs.detachElement(element);
  45447. if (this._reset) {
  45448. this._reset();
  45449. }
  45450. };
  45451. ArcRotateCamera.prototype._checkInputs = function () {
  45452. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45453. if (this._collisionTriggered) {
  45454. return;
  45455. }
  45456. this.inputs.checkInputs();
  45457. // Inertia
  45458. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45459. if (this.getScene().useRightHandedSystem) {
  45460. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45461. }
  45462. else {
  45463. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45464. }
  45465. this.beta += this.inertialBetaOffset;
  45466. this.radius -= this.inertialRadiusOffset;
  45467. this.inertialAlphaOffset *= this.inertia;
  45468. this.inertialBetaOffset *= this.inertia;
  45469. this.inertialRadiusOffset *= this.inertia;
  45470. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45471. this.inertialAlphaOffset = 0;
  45472. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45473. this.inertialBetaOffset = 0;
  45474. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45475. this.inertialRadiusOffset = 0;
  45476. }
  45477. // Panning inertia
  45478. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45479. if (!this._localDirection) {
  45480. this._localDirection = BABYLON.Vector3.Zero();
  45481. this._transformedDirection = BABYLON.Vector3.Zero();
  45482. }
  45483. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45484. this._localDirection.multiplyInPlace(this.panningAxis);
  45485. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45486. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45487. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45488. if (!this.panningAxis.y) {
  45489. this._transformedDirection.y = 0;
  45490. }
  45491. if (!this._targetHost) {
  45492. if (this.panningDistanceLimit) {
  45493. this._transformedDirection.addInPlace(this._target);
  45494. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45495. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45496. this._target.copyFrom(this._transformedDirection);
  45497. }
  45498. }
  45499. else {
  45500. this._target.addInPlace(this._transformedDirection);
  45501. }
  45502. }
  45503. this.inertialPanningX *= this.panningInertia;
  45504. this.inertialPanningY *= this.panningInertia;
  45505. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45506. this.inertialPanningX = 0;
  45507. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45508. this.inertialPanningY = 0;
  45509. }
  45510. // Limits
  45511. this._checkLimits();
  45512. _super.prototype._checkInputs.call(this);
  45513. };
  45514. ArcRotateCamera.prototype._checkLimits = function () {
  45515. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45516. if (this.allowUpsideDown && this.beta > Math.PI) {
  45517. this.beta = this.beta - (2 * Math.PI);
  45518. }
  45519. }
  45520. else {
  45521. if (this.beta < this.lowerBetaLimit) {
  45522. this.beta = this.lowerBetaLimit;
  45523. }
  45524. }
  45525. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45526. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45527. this.beta = this.beta + (2 * Math.PI);
  45528. }
  45529. }
  45530. else {
  45531. if (this.beta > this.upperBetaLimit) {
  45532. this.beta = this.upperBetaLimit;
  45533. }
  45534. }
  45535. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45536. this.alpha = this.lowerAlphaLimit;
  45537. }
  45538. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45539. this.alpha = this.upperAlphaLimit;
  45540. }
  45541. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45542. this.radius = this.lowerRadiusLimit;
  45543. }
  45544. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45545. this.radius = this.upperRadiusLimit;
  45546. }
  45547. };
  45548. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45549. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45550. this.radius = this._computationVector.length();
  45551. if (this.radius === 0) {
  45552. this.radius = 0.0001; // Just to avoid division by zero
  45553. }
  45554. // Alpha
  45555. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45556. if (this._computationVector.z < 0) {
  45557. this.alpha = 2 * Math.PI - this.alpha;
  45558. }
  45559. // Beta
  45560. this.beta = Math.acos(this._computationVector.y / this.radius);
  45561. this._checkLimits();
  45562. };
  45563. ArcRotateCamera.prototype.setPosition = function (position) {
  45564. if (this.position.equals(position)) {
  45565. return;
  45566. }
  45567. this.position.copyFrom(position);
  45568. this.rebuildAnglesAndRadius();
  45569. };
  45570. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45571. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45572. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45573. if (target.getBoundingInfo) {
  45574. if (toBoundingCenter) {
  45575. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45576. }
  45577. else {
  45578. this._targetBoundingCenter = null;
  45579. }
  45580. this._targetHost = target;
  45581. this._target = this._getTargetPosition();
  45582. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45583. }
  45584. else {
  45585. var newTarget = target;
  45586. var currentTarget = this._getTargetPosition();
  45587. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45588. return;
  45589. }
  45590. this._targetHost = null;
  45591. this._target = newTarget;
  45592. this._targetBoundingCenter = null;
  45593. this.onMeshTargetChangedObservable.notifyObservers(null);
  45594. }
  45595. this.rebuildAnglesAndRadius();
  45596. };
  45597. ArcRotateCamera.prototype._getViewMatrix = function () {
  45598. // Compute
  45599. var cosa = Math.cos(this.alpha);
  45600. var sina = Math.sin(this.alpha);
  45601. var cosb = Math.cos(this.beta);
  45602. var sinb = Math.sin(this.beta);
  45603. if (sinb === 0) {
  45604. sinb = 0.0001;
  45605. }
  45606. var target = this._getTargetPosition();
  45607. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45608. target.addToRef(this._computationVector, this._newPosition);
  45609. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45610. if (!this._collider) {
  45611. this._collider = new BABYLON.Collider();
  45612. }
  45613. this._collider._radius = this.collisionRadius;
  45614. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45615. this._collisionTriggered = true;
  45616. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45617. }
  45618. else {
  45619. this.position.copyFrom(this._newPosition);
  45620. var up = this.upVector;
  45621. if (this.allowUpsideDown && sinb < 0) {
  45622. up = up.clone();
  45623. up = up.negate();
  45624. }
  45625. if (this.getScene().useRightHandedSystem) {
  45626. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45627. }
  45628. else {
  45629. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45630. }
  45631. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45632. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45633. }
  45634. this._currentTarget = target;
  45635. return this._viewMatrix;
  45636. };
  45637. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45638. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45639. meshes = meshes || this.getScene().meshes;
  45640. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45641. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45642. this.radius = distance * this.zoomOnFactor;
  45643. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45644. };
  45645. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45646. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45647. var meshesOrMinMaxVector;
  45648. var distance;
  45649. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45650. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45651. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45652. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45653. }
  45654. else {
  45655. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45656. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45657. distance = minMaxVectorAndDistance.distance;
  45658. }
  45659. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45660. if (!doNotUpdateMaxZ) {
  45661. this.maxZ = distance * 2;
  45662. }
  45663. };
  45664. /**
  45665. * @override
  45666. * Override Camera.createRigCamera
  45667. */
  45668. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45669. var alphaShift = 0;
  45670. switch (this.cameraRigMode) {
  45671. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45672. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45673. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45674. case BABYLON.Camera.RIG_MODE_VR:
  45675. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45676. break;
  45677. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45678. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45679. break;
  45680. }
  45681. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45682. rigCam._cameraRigParams = {};
  45683. return rigCam;
  45684. };
  45685. /**
  45686. * @override
  45687. * Override Camera._updateRigCameras
  45688. */
  45689. ArcRotateCamera.prototype._updateRigCameras = function () {
  45690. var camLeft = this._rigCameras[0];
  45691. var camRight = this._rigCameras[1];
  45692. camLeft.beta = camRight.beta = this.beta;
  45693. camLeft.radius = camRight.radius = this.radius;
  45694. switch (this.cameraRigMode) {
  45695. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45696. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45697. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45698. case BABYLON.Camera.RIG_MODE_VR:
  45699. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45700. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45701. break;
  45702. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45703. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45704. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45705. break;
  45706. }
  45707. _super.prototype._updateRigCameras.call(this);
  45708. };
  45709. ArcRotateCamera.prototype.dispose = function () {
  45710. this.inputs.clear();
  45711. _super.prototype.dispose.call(this);
  45712. };
  45713. ArcRotateCamera.prototype.getClassName = function () {
  45714. return "ArcRotateCamera";
  45715. };
  45716. __decorate([
  45717. BABYLON.serialize()
  45718. ], ArcRotateCamera.prototype, "alpha", void 0);
  45719. __decorate([
  45720. BABYLON.serialize()
  45721. ], ArcRotateCamera.prototype, "beta", void 0);
  45722. __decorate([
  45723. BABYLON.serialize()
  45724. ], ArcRotateCamera.prototype, "radius", void 0);
  45725. __decorate([
  45726. BABYLON.serializeAsVector3("target")
  45727. ], ArcRotateCamera.prototype, "_target", void 0);
  45728. __decorate([
  45729. BABYLON.serialize()
  45730. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45731. __decorate([
  45732. BABYLON.serialize()
  45733. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45734. __decorate([
  45735. BABYLON.serialize()
  45736. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45737. __decorate([
  45738. BABYLON.serialize()
  45739. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45740. __decorate([
  45741. BABYLON.serialize()
  45742. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45743. __decorate([
  45744. BABYLON.serialize()
  45745. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45746. __decorate([
  45747. BABYLON.serialize()
  45748. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45749. __decorate([
  45750. BABYLON.serialize()
  45751. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45752. __decorate([
  45753. BABYLON.serialize()
  45754. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45755. __decorate([
  45756. BABYLON.serialize()
  45757. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45758. __decorate([
  45759. BABYLON.serialize()
  45760. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45761. __decorate([
  45762. BABYLON.serialize()
  45763. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45764. __decorate([
  45765. BABYLON.serialize()
  45766. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45767. __decorate([
  45768. BABYLON.serializeAsVector3()
  45769. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45770. __decorate([
  45771. BABYLON.serialize()
  45772. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45773. __decorate([
  45774. BABYLON.serialize()
  45775. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45776. __decorate([
  45777. BABYLON.serialize()
  45778. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45779. return ArcRotateCamera;
  45780. }(BABYLON.TargetCamera));
  45781. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45782. })(BABYLON || (BABYLON = {}));
  45783. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45784. "use strict";
  45785. var BABYLON;
  45786. (function (BABYLON) {
  45787. /**
  45788. * The HemisphericLight simulates the ambient environment light,
  45789. * so the passed direction is the light reflection direction, not the incoming direction.
  45790. */
  45791. var HemisphericLight = /** @class */ (function (_super) {
  45792. __extends(HemisphericLight, _super);
  45793. /**
  45794. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45795. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45796. * The HemisphericLight can't cast shadows.
  45797. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45798. * @param name The friendly name of the light
  45799. * @param direction The direction of the light reflection
  45800. * @param scene The scene the light belongs to
  45801. */
  45802. function HemisphericLight(name, direction, scene) {
  45803. var _this = _super.call(this, name, scene) || this;
  45804. /**
  45805. * The groundColor is the light in the opposite direction to the one specified during creation.
  45806. * 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.
  45807. */
  45808. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45809. _this.direction = direction || BABYLON.Vector3.Up();
  45810. return _this;
  45811. }
  45812. HemisphericLight.prototype._buildUniformLayout = function () {
  45813. this._uniformBuffer.addUniform("vLightData", 4);
  45814. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45815. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45816. this._uniformBuffer.addUniform("vLightGround", 3);
  45817. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45818. this._uniformBuffer.addUniform("depthValues", 2);
  45819. this._uniformBuffer.create();
  45820. };
  45821. /**
  45822. * Returns the string "HemisphericLight".
  45823. * @return The class name
  45824. */
  45825. HemisphericLight.prototype.getClassName = function () {
  45826. return "HemisphericLight";
  45827. };
  45828. /**
  45829. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45830. * Returns the updated direction.
  45831. * @param target The target the direction should point to
  45832. * @return The computed direction
  45833. */
  45834. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45835. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45836. return this.direction;
  45837. };
  45838. /**
  45839. * Returns the shadow generator associated to the light.
  45840. * @returns Always null for hemispheric lights because it does not support shadows.
  45841. */
  45842. HemisphericLight.prototype.getShadowGenerator = function () {
  45843. return null;
  45844. };
  45845. /**
  45846. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45847. * @param effect The effect to update
  45848. * @param lightIndex The index of the light in the effect to update
  45849. * @returns The hemispheric light
  45850. */
  45851. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45852. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45853. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45854. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45855. return this;
  45856. };
  45857. /**
  45858. * @ignore internal use only.
  45859. */
  45860. HemisphericLight.prototype._getWorldMatrix = function () {
  45861. if (!this._worldMatrix) {
  45862. this._worldMatrix = BABYLON.Matrix.Identity();
  45863. }
  45864. return this._worldMatrix;
  45865. };
  45866. /**
  45867. * Returns the integer 3.
  45868. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45869. */
  45870. HemisphericLight.prototype.getTypeID = function () {
  45871. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45872. };
  45873. __decorate([
  45874. BABYLON.serializeAsColor3()
  45875. ], HemisphericLight.prototype, "groundColor", void 0);
  45876. __decorate([
  45877. BABYLON.serializeAsVector3()
  45878. ], HemisphericLight.prototype, "direction", void 0);
  45879. return HemisphericLight;
  45880. }(BABYLON.Light));
  45881. BABYLON.HemisphericLight = HemisphericLight;
  45882. })(BABYLON || (BABYLON = {}));
  45883. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45884. "use strict";
  45885. var BABYLON;
  45886. (function (BABYLON) {
  45887. /**
  45888. * Base implementation of @see IShadowLight
  45889. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45890. */
  45891. var ShadowLight = /** @class */ (function (_super) {
  45892. __extends(ShadowLight, _super);
  45893. function ShadowLight() {
  45894. var _this = _super !== null && _super.apply(this, arguments) || this;
  45895. _this._needProjectionMatrixCompute = true;
  45896. return _this;
  45897. }
  45898. ShadowLight.prototype._setPosition = function (value) {
  45899. this._position = value;
  45900. };
  45901. Object.defineProperty(ShadowLight.prototype, "position", {
  45902. /**
  45903. * Sets the position the shadow will be casted from. Also use as the light position for both
  45904. * point and spot lights.
  45905. */
  45906. get: function () {
  45907. return this._position;
  45908. },
  45909. /**
  45910. * Sets the position the shadow will be casted from. Also use as the light position for both
  45911. * point and spot lights.
  45912. */
  45913. set: function (value) {
  45914. this._setPosition(value);
  45915. },
  45916. enumerable: true,
  45917. configurable: true
  45918. });
  45919. ShadowLight.prototype._setDirection = function (value) {
  45920. this._direction = value;
  45921. };
  45922. Object.defineProperty(ShadowLight.prototype, "direction", {
  45923. /**
  45924. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45925. * Also use as the light direction on spot and directional lights.
  45926. */
  45927. get: function () {
  45928. return this._direction;
  45929. },
  45930. /**
  45931. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45932. * Also use as the light direction on spot and directional lights.
  45933. */
  45934. set: function (value) {
  45935. this._setDirection(value);
  45936. },
  45937. enumerable: true,
  45938. configurable: true
  45939. });
  45940. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45941. /**
  45942. * Gets the shadow projection clipping minimum z value.
  45943. */
  45944. get: function () {
  45945. return this._shadowMinZ;
  45946. },
  45947. /**
  45948. * Sets the shadow projection clipping minimum z value.
  45949. */
  45950. set: function (value) {
  45951. this._shadowMinZ = value;
  45952. this.forceProjectionMatrixCompute();
  45953. },
  45954. enumerable: true,
  45955. configurable: true
  45956. });
  45957. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45958. /**
  45959. * Sets the shadow projection clipping maximum z value.
  45960. */
  45961. get: function () {
  45962. return this._shadowMaxZ;
  45963. },
  45964. /**
  45965. * Gets the shadow projection clipping maximum z value.
  45966. */
  45967. set: function (value) {
  45968. this._shadowMaxZ = value;
  45969. this.forceProjectionMatrixCompute();
  45970. },
  45971. enumerable: true,
  45972. configurable: true
  45973. });
  45974. /**
  45975. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45976. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45977. */
  45978. ShadowLight.prototype.computeTransformedInformation = function () {
  45979. if (this.parent && this.parent.getWorldMatrix) {
  45980. if (!this.transformedPosition) {
  45981. this.transformedPosition = BABYLON.Vector3.Zero();
  45982. }
  45983. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45984. // In case the direction is present.
  45985. if (this.direction) {
  45986. if (!this.transformedDirection) {
  45987. this.transformedDirection = BABYLON.Vector3.Zero();
  45988. }
  45989. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45990. }
  45991. return true;
  45992. }
  45993. return false;
  45994. };
  45995. /**
  45996. * Return the depth scale used for the shadow map.
  45997. * @returns the depth scale.
  45998. */
  45999. ShadowLight.prototype.getDepthScale = function () {
  46000. return 50.0;
  46001. };
  46002. /**
  46003. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  46004. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46005. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46006. */
  46007. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  46008. return this.transformedDirection ? this.transformedDirection : this.direction;
  46009. };
  46010. /**
  46011. * Returns the ShadowLight absolute position in the World.
  46012. * @returns the position vector in world space
  46013. */
  46014. ShadowLight.prototype.getAbsolutePosition = function () {
  46015. return this.transformedPosition ? this.transformedPosition : this.position;
  46016. };
  46017. /**
  46018. * Sets the ShadowLight direction toward the passed target.
  46019. * @param target The point tot target in local space
  46020. * @returns the updated ShadowLight direction
  46021. */
  46022. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46023. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46024. return this.direction;
  46025. };
  46026. /**
  46027. * Returns the light rotation in euler definition.
  46028. * @returns the x y z rotation in local space.
  46029. */
  46030. ShadowLight.prototype.getRotation = function () {
  46031. this.direction.normalize();
  46032. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46033. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46034. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46035. };
  46036. /**
  46037. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46038. * @returns true if a cube texture needs to be use
  46039. */
  46040. ShadowLight.prototype.needCube = function () {
  46041. return false;
  46042. };
  46043. /**
  46044. * Detects if the projection matrix requires to be recomputed this frame.
  46045. * @returns true if it requires to be recomputed otherwise, false.
  46046. */
  46047. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46048. return this._needProjectionMatrixCompute;
  46049. };
  46050. /**
  46051. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46052. */
  46053. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46054. this._needProjectionMatrixCompute = true;
  46055. };
  46056. /**
  46057. * Get the world matrix of the sahdow lights.
  46058. * @ignore Internal Use Only
  46059. */
  46060. ShadowLight.prototype._getWorldMatrix = function () {
  46061. if (!this._worldMatrix) {
  46062. this._worldMatrix = BABYLON.Matrix.Identity();
  46063. }
  46064. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46065. return this._worldMatrix;
  46066. };
  46067. /**
  46068. * Gets the minZ used for shadow according to both the scene and the light.
  46069. * @param activeCamera The camera we are returning the min for
  46070. * @returns the depth min z
  46071. */
  46072. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46073. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46074. };
  46075. /**
  46076. * Gets the maxZ used for shadow according to both the scene and the light.
  46077. * @param activeCamera The camera we are returning the max for
  46078. * @returns the depth max z
  46079. */
  46080. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46081. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46082. };
  46083. /**
  46084. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46085. * @param matrix The materix to updated with the projection information
  46086. * @param viewMatrix The transform matrix of the light
  46087. * @param renderList The list of mesh to render in the map
  46088. * @returns The current light
  46089. */
  46090. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46091. if (this.customProjectionMatrixBuilder) {
  46092. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46093. }
  46094. else {
  46095. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46096. }
  46097. return this;
  46098. };
  46099. __decorate([
  46100. BABYLON.serializeAsVector3()
  46101. ], ShadowLight.prototype, "position", null);
  46102. __decorate([
  46103. BABYLON.serializeAsVector3()
  46104. ], ShadowLight.prototype, "direction", null);
  46105. __decorate([
  46106. BABYLON.serialize()
  46107. ], ShadowLight.prototype, "shadowMinZ", null);
  46108. __decorate([
  46109. BABYLON.serialize()
  46110. ], ShadowLight.prototype, "shadowMaxZ", null);
  46111. return ShadowLight;
  46112. }(BABYLON.Light));
  46113. BABYLON.ShadowLight = ShadowLight;
  46114. })(BABYLON || (BABYLON = {}));
  46115. //# sourceMappingURL=babylon.shadowLight.js.map
  46116. "use strict";
  46117. var BABYLON;
  46118. (function (BABYLON) {
  46119. /**
  46120. * A point light is a light defined by an unique point in world space.
  46121. * The light is emitted in every direction from this point.
  46122. * A good example of a point light is a standard light bulb.
  46123. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46124. */
  46125. var PointLight = /** @class */ (function (_super) {
  46126. __extends(PointLight, _super);
  46127. /**
  46128. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46129. * A PointLight emits the light in every direction.
  46130. * It can cast shadows.
  46131. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46132. * ```javascript
  46133. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46134. * ```
  46135. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46136. * @param name The light friendly name
  46137. * @param position The position of the point light in the scene
  46138. * @param scene The scene the lights belongs to
  46139. */
  46140. function PointLight(name, position, scene) {
  46141. var _this = _super.call(this, name, scene) || this;
  46142. _this._shadowAngle = Math.PI / 2;
  46143. _this.position = position;
  46144. return _this;
  46145. }
  46146. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46147. /**
  46148. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46149. * This specifies what angle the shadow will use to be created.
  46150. *
  46151. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46152. */
  46153. get: function () {
  46154. return this._shadowAngle;
  46155. },
  46156. /**
  46157. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46158. * This specifies what angle the shadow will use to be created.
  46159. *
  46160. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46161. */
  46162. set: function (value) {
  46163. this._shadowAngle = value;
  46164. this.forceProjectionMatrixCompute();
  46165. },
  46166. enumerable: true,
  46167. configurable: true
  46168. });
  46169. Object.defineProperty(PointLight.prototype, "direction", {
  46170. /**
  46171. * Gets the direction if it has been set.
  46172. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46173. */
  46174. get: function () {
  46175. return this._direction;
  46176. },
  46177. /**
  46178. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46179. */
  46180. set: function (value) {
  46181. var previousNeedCube = this.needCube();
  46182. this._direction = value;
  46183. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46184. this._shadowGenerator.recreateShadowMap();
  46185. }
  46186. },
  46187. enumerable: true,
  46188. configurable: true
  46189. });
  46190. /**
  46191. * Returns the string "PointLight"
  46192. * @returns the class name
  46193. */
  46194. PointLight.prototype.getClassName = function () {
  46195. return "PointLight";
  46196. };
  46197. /**
  46198. * Returns the integer 0.
  46199. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46200. */
  46201. PointLight.prototype.getTypeID = function () {
  46202. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46203. };
  46204. /**
  46205. * Specifies wether or not the shadowmap should be a cube texture.
  46206. * @returns true if the shadowmap needs to be a cube texture.
  46207. */
  46208. PointLight.prototype.needCube = function () {
  46209. return !this.direction;
  46210. };
  46211. /**
  46212. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46213. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46214. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46215. */
  46216. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46217. if (this.direction) {
  46218. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46219. }
  46220. else {
  46221. switch (faceIndex) {
  46222. case 0:
  46223. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46224. case 1:
  46225. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46226. case 2:
  46227. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46228. case 3:
  46229. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46230. case 4:
  46231. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46232. case 5:
  46233. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46234. }
  46235. }
  46236. return BABYLON.Vector3.Zero();
  46237. };
  46238. /**
  46239. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46240. * - fov = PI / 2
  46241. * - aspect ratio : 1.0
  46242. * - z-near and far equal to the active camera minZ and maxZ.
  46243. * Returns the PointLight.
  46244. */
  46245. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46246. var activeCamera = this.getScene().activeCamera;
  46247. if (!activeCamera) {
  46248. return;
  46249. }
  46250. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46251. };
  46252. PointLight.prototype._buildUniformLayout = function () {
  46253. this._uniformBuffer.addUniform("vLightData", 4);
  46254. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46255. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46256. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46257. this._uniformBuffer.addUniform("depthValues", 2);
  46258. this._uniformBuffer.create();
  46259. };
  46260. /**
  46261. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46262. * @param effect The effect to update
  46263. * @param lightIndex The index of the light in the effect to update
  46264. * @returns The point light
  46265. */
  46266. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46267. if (this.computeTransformedInformation()) {
  46268. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46269. return this;
  46270. }
  46271. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46272. return this;
  46273. };
  46274. __decorate([
  46275. BABYLON.serialize()
  46276. ], PointLight.prototype, "shadowAngle", null);
  46277. return PointLight;
  46278. }(BABYLON.ShadowLight));
  46279. BABYLON.PointLight = PointLight;
  46280. })(BABYLON || (BABYLON = {}));
  46281. //# sourceMappingURL=babylon.pointLight.js.map
  46282. "use strict";
  46283. var BABYLON;
  46284. (function (BABYLON) {
  46285. /**
  46286. * A directional light is defined by a direction (what a surprise!).
  46287. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46288. * 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.
  46289. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46290. */
  46291. var DirectionalLight = /** @class */ (function (_super) {
  46292. __extends(DirectionalLight, _super);
  46293. /**
  46294. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46295. * The directional light is emitted from everywhere in the given direction.
  46296. * It can cast shawdows.
  46297. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46298. * @param name The friendly name of the light
  46299. * @param direction The direction of the light
  46300. * @param scene The scene the light belongs to
  46301. */
  46302. function DirectionalLight(name, direction, scene) {
  46303. var _this = _super.call(this, name, scene) || this;
  46304. _this._shadowFrustumSize = 0;
  46305. _this._shadowOrthoScale = 0.1;
  46306. /**
  46307. * Automatically compute the projection matrix to best fit (including all the casters)
  46308. * on each frame.
  46309. */
  46310. _this.autoUpdateExtends = true;
  46311. // Cache
  46312. _this._orthoLeft = Number.MAX_VALUE;
  46313. _this._orthoRight = Number.MIN_VALUE;
  46314. _this._orthoTop = Number.MIN_VALUE;
  46315. _this._orthoBottom = Number.MAX_VALUE;
  46316. _this.position = direction.scale(-1.0);
  46317. _this.direction = direction;
  46318. return _this;
  46319. }
  46320. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46321. /**
  46322. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46323. */
  46324. get: function () {
  46325. return this._shadowFrustumSize;
  46326. },
  46327. /**
  46328. * Specifies a fix frustum size for the shadow generation.
  46329. */
  46330. set: function (value) {
  46331. this._shadowFrustumSize = value;
  46332. this.forceProjectionMatrixCompute();
  46333. },
  46334. enumerable: true,
  46335. configurable: true
  46336. });
  46337. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46338. /**
  46339. * Gets the shadow projection scale against the optimal computed one.
  46340. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46341. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46342. */
  46343. get: function () {
  46344. return this._shadowOrthoScale;
  46345. },
  46346. /**
  46347. * Sets the shadow projection scale against the optimal computed one.
  46348. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46349. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46350. */
  46351. set: function (value) {
  46352. this._shadowOrthoScale = value;
  46353. this.forceProjectionMatrixCompute();
  46354. },
  46355. enumerable: true,
  46356. configurable: true
  46357. });
  46358. /**
  46359. * Returns the string "DirectionalLight".
  46360. * @return The class name
  46361. */
  46362. DirectionalLight.prototype.getClassName = function () {
  46363. return "DirectionalLight";
  46364. };
  46365. /**
  46366. * Returns the integer 1.
  46367. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46368. */
  46369. DirectionalLight.prototype.getTypeID = function () {
  46370. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46371. };
  46372. /**
  46373. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46374. * Returns the DirectionalLight Shadow projection matrix.
  46375. */
  46376. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46377. if (this.shadowFrustumSize > 0) {
  46378. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46379. }
  46380. else {
  46381. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46382. }
  46383. };
  46384. /**
  46385. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46386. * Returns the DirectionalLight Shadow projection matrix.
  46387. */
  46388. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46389. var activeCamera = this.getScene().activeCamera;
  46390. if (!activeCamera) {
  46391. return;
  46392. }
  46393. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46394. };
  46395. /**
  46396. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46397. * Returns the DirectionalLight Shadow projection matrix.
  46398. */
  46399. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46400. var activeCamera = this.getScene().activeCamera;
  46401. if (!activeCamera) {
  46402. return;
  46403. }
  46404. // Check extends
  46405. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46406. var tempVector3 = BABYLON.Vector3.Zero();
  46407. this._orthoLeft = Number.MAX_VALUE;
  46408. this._orthoRight = Number.MIN_VALUE;
  46409. this._orthoTop = Number.MIN_VALUE;
  46410. this._orthoBottom = Number.MAX_VALUE;
  46411. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46412. var mesh = renderList[meshIndex];
  46413. if (!mesh) {
  46414. continue;
  46415. }
  46416. var boundingInfo = mesh.getBoundingInfo();
  46417. var boundingBox = boundingInfo.boundingBox;
  46418. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46419. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46420. if (tempVector3.x < this._orthoLeft)
  46421. this._orthoLeft = tempVector3.x;
  46422. if (tempVector3.y < this._orthoBottom)
  46423. this._orthoBottom = tempVector3.y;
  46424. if (tempVector3.x > this._orthoRight)
  46425. this._orthoRight = tempVector3.x;
  46426. if (tempVector3.y > this._orthoTop)
  46427. this._orthoTop = tempVector3.y;
  46428. }
  46429. }
  46430. }
  46431. var xOffset = this._orthoRight - this._orthoLeft;
  46432. var yOffset = this._orthoTop - this._orthoBottom;
  46433. 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);
  46434. };
  46435. DirectionalLight.prototype._buildUniformLayout = function () {
  46436. this._uniformBuffer.addUniform("vLightData", 4);
  46437. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46438. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46439. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46440. this._uniformBuffer.addUniform("depthValues", 2);
  46441. this._uniformBuffer.create();
  46442. };
  46443. /**
  46444. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46445. * @param effect The effect to update
  46446. * @param lightIndex The index of the light in the effect to update
  46447. * @returns The directional light
  46448. */
  46449. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46450. if (this.computeTransformedInformation()) {
  46451. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46452. return this;
  46453. }
  46454. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46455. return this;
  46456. };
  46457. /**
  46458. * Gets the minZ used for shadow according to both the scene and the light.
  46459. *
  46460. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46461. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46462. * @param activeCamera The camera we are returning the min for
  46463. * @returns the depth min z
  46464. */
  46465. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46466. return 1;
  46467. };
  46468. /**
  46469. * Gets the maxZ used for shadow according to both the scene and the light.
  46470. *
  46471. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46472. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46473. * @param activeCamera The camera we are returning the max for
  46474. * @returns the depth max z
  46475. */
  46476. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46477. return 1;
  46478. };
  46479. __decorate([
  46480. BABYLON.serialize()
  46481. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46482. __decorate([
  46483. BABYLON.serialize()
  46484. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46485. __decorate([
  46486. BABYLON.serialize()
  46487. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46488. return DirectionalLight;
  46489. }(BABYLON.ShadowLight));
  46490. BABYLON.DirectionalLight = DirectionalLight;
  46491. })(BABYLON || (BABYLON = {}));
  46492. //# sourceMappingURL=babylon.directionalLight.js.map
  46493. "use strict";
  46494. var BABYLON;
  46495. (function (BABYLON) {
  46496. /**
  46497. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46498. * These values define a cone of light starting from the position, emitting toward the direction.
  46499. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46500. * and the exponent defines the speed of the decay of the light with distance (reach).
  46501. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46502. */
  46503. var SpotLight = /** @class */ (function (_super) {
  46504. __extends(SpotLight, _super);
  46505. /**
  46506. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46507. * It can cast shadows.
  46508. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46509. * @param name The light friendly name
  46510. * @param position The position of the spot light in the scene
  46511. * @param direction The direction of the light in the scene
  46512. * @param angle The cone angle of the light in Radians
  46513. * @param exponent The light decay speed with the distance from the emission spot
  46514. * @param scene The scene the lights belongs to
  46515. */
  46516. function SpotLight(name, position, direction, angle, exponent, scene) {
  46517. var _this = _super.call(this, name, scene) || this;
  46518. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46519. _this._projectionTextureLightNear = 1e-6;
  46520. _this._projectionTextureLightFar = 1000.0;
  46521. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46522. _this._projectionTextureViewLightDirty = true;
  46523. _this._projectionTextureProjectionLightDirty = true;
  46524. _this._projectionTextureDirty = true;
  46525. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46526. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46527. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46528. _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);
  46529. _this.position = position;
  46530. _this.direction = direction;
  46531. _this.angle = angle;
  46532. _this.exponent = exponent;
  46533. return _this;
  46534. }
  46535. Object.defineProperty(SpotLight.prototype, "angle", {
  46536. /**
  46537. * Gets the cone angle of the spot light in Radians.
  46538. */
  46539. get: function () {
  46540. return this._angle;
  46541. },
  46542. /**
  46543. * Sets the cone angle of the spot light in Radians.
  46544. */
  46545. set: function (value) {
  46546. this._angle = value;
  46547. this._projectionTextureProjectionLightDirty = true;
  46548. this.forceProjectionMatrixCompute();
  46549. },
  46550. enumerable: true,
  46551. configurable: true
  46552. });
  46553. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46554. /**
  46555. * Allows scaling the angle of the light for shadow generation only.
  46556. */
  46557. get: function () {
  46558. return this._shadowAngleScale;
  46559. },
  46560. /**
  46561. * Allows scaling the angle of the light for shadow generation only.
  46562. */
  46563. set: function (value) {
  46564. this._shadowAngleScale = value;
  46565. this.forceProjectionMatrixCompute();
  46566. },
  46567. enumerable: true,
  46568. configurable: true
  46569. });
  46570. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46571. /**
  46572. * Allows reading the projecton texture
  46573. */
  46574. get: function () {
  46575. return this._projectionTextureMatrix;
  46576. },
  46577. enumerable: true,
  46578. configurable: true
  46579. });
  46580. ;
  46581. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46582. /**
  46583. * Gets the near clip of the Spotlight for texture projection.
  46584. */
  46585. get: function () {
  46586. return this._projectionTextureLightNear;
  46587. },
  46588. /**
  46589. * Sets the near clip of the Spotlight for texture projection.
  46590. */
  46591. set: function (value) {
  46592. this._projectionTextureLightNear = value;
  46593. this._projectionTextureProjectionLightDirty = true;
  46594. },
  46595. enumerable: true,
  46596. configurable: true
  46597. });
  46598. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46599. /**
  46600. * Gets the far clip of the Spotlight for texture projection.
  46601. */
  46602. get: function () {
  46603. return this._projectionTextureLightFar;
  46604. },
  46605. /**
  46606. * Sets the far clip of the Spotlight for texture projection.
  46607. */
  46608. set: function (value) {
  46609. this._projectionTextureLightFar = value;
  46610. this._projectionTextureProjectionLightDirty = true;
  46611. },
  46612. enumerable: true,
  46613. configurable: true
  46614. });
  46615. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46616. /**
  46617. * Gets the Up vector of the Spotlight for texture projection.
  46618. */
  46619. get: function () {
  46620. return this._projectionTextureUpDirection;
  46621. },
  46622. /**
  46623. * Sets the Up vector of the Spotlight for texture projection.
  46624. */
  46625. set: function (value) {
  46626. this._projectionTextureUpDirection = value;
  46627. this._projectionTextureProjectionLightDirty = true;
  46628. },
  46629. enumerable: true,
  46630. configurable: true
  46631. });
  46632. ;
  46633. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46634. /**
  46635. * Gets the projection texture of the light.
  46636. */
  46637. get: function () {
  46638. return this._projectionTexture;
  46639. },
  46640. /**
  46641. * Sets the projection texture of the light.
  46642. */
  46643. set: function (value) {
  46644. this._projectionTexture = value;
  46645. this._projectionTextureDirty = true;
  46646. },
  46647. enumerable: true,
  46648. configurable: true
  46649. });
  46650. /**
  46651. * Returns the string "SpotLight".
  46652. * @returns the class name
  46653. */
  46654. SpotLight.prototype.getClassName = function () {
  46655. return "SpotLight";
  46656. };
  46657. /**
  46658. * Returns the integer 2.
  46659. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46660. */
  46661. SpotLight.prototype.getTypeID = function () {
  46662. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46663. };
  46664. /**
  46665. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46666. */
  46667. SpotLight.prototype._setDirection = function (value) {
  46668. _super.prototype._setDirection.call(this, value);
  46669. this._projectionTextureViewLightDirty = true;
  46670. };
  46671. /**
  46672. * Overrides the position setter to recompute the projection texture view light Matrix.
  46673. */
  46674. SpotLight.prototype._setPosition = function (value) {
  46675. _super.prototype._setPosition.call(this, value);
  46676. this._projectionTextureViewLightDirty = true;
  46677. };
  46678. /**
  46679. * 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.
  46680. * Returns the SpotLight.
  46681. */
  46682. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46683. var activeCamera = this.getScene().activeCamera;
  46684. if (!activeCamera) {
  46685. return;
  46686. }
  46687. this._shadowAngleScale = this._shadowAngleScale || 1;
  46688. var angle = this._shadowAngleScale * this._angle;
  46689. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46690. };
  46691. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46692. this._projectionTextureViewLightDirty = false;
  46693. this._projectionTextureDirty = true;
  46694. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46695. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46696. };
  46697. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46698. this._projectionTextureProjectionLightDirty = false;
  46699. this._projectionTextureDirty = true;
  46700. var light_far = this.projectionTextureLightFar;
  46701. var light_near = this.projectionTextureLightNear;
  46702. var P = light_far / (light_far - light_near);
  46703. var Q = -P * light_near;
  46704. var S = 1.0 / Math.tan(this._angle / 2.0);
  46705. var A = 1.0;
  46706. 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);
  46707. };
  46708. /**
  46709. * Main function for light texture projection matrix computing.
  46710. */
  46711. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46712. this._projectionTextureDirty = false;
  46713. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46714. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46715. };
  46716. SpotLight.prototype._buildUniformLayout = function () {
  46717. this._uniformBuffer.addUniform("vLightData", 4);
  46718. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46719. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46720. this._uniformBuffer.addUniform("vLightDirection", 3);
  46721. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46722. this._uniformBuffer.addUniform("depthValues", 2);
  46723. this._uniformBuffer.create();
  46724. };
  46725. /**
  46726. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46727. * @param effect The effect to update
  46728. * @param lightIndex The index of the light in the effect to update
  46729. * @returns The spot light
  46730. */
  46731. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46732. var normalizeDirection;
  46733. if (this.computeTransformedInformation()) {
  46734. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46735. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46736. }
  46737. else {
  46738. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46739. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46740. }
  46741. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46742. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46743. if (this._projectionTextureViewLightDirty) {
  46744. this._computeProjectionTextureViewLightMatrix();
  46745. }
  46746. if (this._projectionTextureProjectionLightDirty) {
  46747. this._computeProjectionTextureProjectionLightMatrix();
  46748. }
  46749. if (this._projectionTextureDirty) {
  46750. this._computeProjectionTextureMatrix();
  46751. }
  46752. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46753. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46754. }
  46755. return this;
  46756. };
  46757. /**
  46758. * Disposes the light and the associated resources.
  46759. */
  46760. SpotLight.prototype.dispose = function () {
  46761. _super.prototype.dispose.call(this);
  46762. if (this._projectionTexture) {
  46763. this._projectionTexture.dispose();
  46764. }
  46765. };
  46766. __decorate([
  46767. BABYLON.serialize()
  46768. ], SpotLight.prototype, "angle", null);
  46769. __decorate([
  46770. BABYLON.serialize()
  46771. ], SpotLight.prototype, "shadowAngleScale", null);
  46772. __decorate([
  46773. BABYLON.serialize()
  46774. ], SpotLight.prototype, "exponent", void 0);
  46775. __decorate([
  46776. BABYLON.serialize()
  46777. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46778. __decorate([
  46779. BABYLON.serialize()
  46780. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46781. __decorate([
  46782. BABYLON.serialize()
  46783. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46784. __decorate([
  46785. BABYLON.serializeAsTexture("projectedLightTexture")
  46786. ], SpotLight.prototype, "_projectionTexture", void 0);
  46787. return SpotLight;
  46788. }(BABYLON.ShadowLight));
  46789. BABYLON.SpotLight = SpotLight;
  46790. })(BABYLON || (BABYLON = {}));
  46791. //# sourceMappingURL=babylon.spotLight.js.map
  46792. "use strict";
  46793. var BABYLON;
  46794. (function (BABYLON) {
  46795. /**
  46796. * Class used to override all child animations of a given target
  46797. */
  46798. var AnimationPropertiesOverride = /** @class */ (function () {
  46799. function AnimationPropertiesOverride() {
  46800. /**
  46801. * Gets or sets a value indicating if animation blending must be used
  46802. */
  46803. this.enableBlending = false;
  46804. /**
  46805. * Gets or sets the blending speed to use when enableBlending is true
  46806. */
  46807. this.blendingSpeed = 0.01;
  46808. /**
  46809. * Gets or sets the default loop mode to use
  46810. */
  46811. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46812. }
  46813. return AnimationPropertiesOverride;
  46814. }());
  46815. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46816. })(BABYLON || (BABYLON = {}));
  46817. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46818. "use strict";
  46819. var BABYLON;
  46820. (function (BABYLON) {
  46821. var AnimationRange = /** @class */ (function () {
  46822. function AnimationRange(name, from, to) {
  46823. this.name = name;
  46824. this.from = from;
  46825. this.to = to;
  46826. }
  46827. AnimationRange.prototype.clone = function () {
  46828. return new AnimationRange(this.name, this.from, this.to);
  46829. };
  46830. return AnimationRange;
  46831. }());
  46832. BABYLON.AnimationRange = AnimationRange;
  46833. /**
  46834. * Composed of a frame, and an action function
  46835. */
  46836. var AnimationEvent = /** @class */ (function () {
  46837. function AnimationEvent(frame, action, onlyOnce) {
  46838. this.frame = frame;
  46839. this.action = action;
  46840. this.onlyOnce = onlyOnce;
  46841. this.isDone = false;
  46842. }
  46843. return AnimationEvent;
  46844. }());
  46845. BABYLON.AnimationEvent = AnimationEvent;
  46846. var PathCursor = /** @class */ (function () {
  46847. function PathCursor(path) {
  46848. this.path = path;
  46849. this._onchange = new Array();
  46850. this.value = 0;
  46851. this.animations = new Array();
  46852. }
  46853. PathCursor.prototype.getPoint = function () {
  46854. var point = this.path.getPointAtLengthPosition(this.value);
  46855. return new BABYLON.Vector3(point.x, 0, point.y);
  46856. };
  46857. PathCursor.prototype.moveAhead = function (step) {
  46858. if (step === void 0) { step = 0.002; }
  46859. this.move(step);
  46860. return this;
  46861. };
  46862. PathCursor.prototype.moveBack = function (step) {
  46863. if (step === void 0) { step = 0.002; }
  46864. this.move(-step);
  46865. return this;
  46866. };
  46867. PathCursor.prototype.move = function (step) {
  46868. if (Math.abs(step) > 1) {
  46869. throw "step size should be less than 1.";
  46870. }
  46871. this.value += step;
  46872. this.ensureLimits();
  46873. this.raiseOnChange();
  46874. return this;
  46875. };
  46876. PathCursor.prototype.ensureLimits = function () {
  46877. while (this.value > 1) {
  46878. this.value -= 1;
  46879. }
  46880. while (this.value < 0) {
  46881. this.value += 1;
  46882. }
  46883. return this;
  46884. };
  46885. // used by animation engine
  46886. PathCursor.prototype.raiseOnChange = function () {
  46887. var _this = this;
  46888. this._onchange.forEach(function (f) { return f(_this); });
  46889. return this;
  46890. };
  46891. PathCursor.prototype.onchange = function (f) {
  46892. this._onchange.push(f);
  46893. return this;
  46894. };
  46895. return PathCursor;
  46896. }());
  46897. BABYLON.PathCursor = PathCursor;
  46898. var AnimationKeyInterpolation;
  46899. (function (AnimationKeyInterpolation) {
  46900. /**
  46901. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46902. */
  46903. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46904. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46905. var Animation = /** @class */ (function () {
  46906. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46907. this.name = name;
  46908. this.targetProperty = targetProperty;
  46909. this.framePerSecond = framePerSecond;
  46910. this.dataType = dataType;
  46911. this.loopMode = loopMode;
  46912. this.enableBlending = enableBlending;
  46913. this._runtimeAnimations = new Array();
  46914. // The set of event that will be linked to this animation
  46915. this._events = new Array();
  46916. this.blendingSpeed = 0.01;
  46917. this._ranges = {};
  46918. this.targetPropertyPath = targetProperty.split(".");
  46919. this.dataType = dataType;
  46920. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46921. }
  46922. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46923. var dataType = undefined;
  46924. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46925. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46926. }
  46927. else if (from instanceof BABYLON.Quaternion) {
  46928. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46929. }
  46930. else if (from instanceof BABYLON.Vector3) {
  46931. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46932. }
  46933. else if (from instanceof BABYLON.Vector2) {
  46934. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46935. }
  46936. else if (from instanceof BABYLON.Color3) {
  46937. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46938. }
  46939. else if (from instanceof BABYLON.Size) {
  46940. dataType = Animation.ANIMATIONTYPE_SIZE;
  46941. }
  46942. if (dataType == undefined) {
  46943. return null;
  46944. }
  46945. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46946. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46947. animation.setKeys(keys);
  46948. if (easingFunction !== undefined) {
  46949. animation.setEasingFunction(easingFunction);
  46950. }
  46951. return animation;
  46952. };
  46953. /**
  46954. * Sets up an animation.
  46955. * @param property the property to animate
  46956. * @param animationType the animation type to apply
  46957. * @param easingFunction the easing function used in the animation
  46958. * @returns The created animation
  46959. */
  46960. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46961. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46962. animation.setEasingFunction(easingFunction);
  46963. return animation;
  46964. };
  46965. /**
  46966. * Create and start an animation on a node
  46967. * @param {string} name defines the name of the global animation that will be run on all nodes
  46968. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46969. * @param {string} targetProperty defines property to animate
  46970. * @param {number} framePerSecond defines the number of frame per second yo use
  46971. * @param {number} totalFrame defines the number of frames in total
  46972. * @param {any} from defines the initial value
  46973. * @param {any} to defines the final value
  46974. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46975. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46976. * @param onAnimationEnd defines the callback to call when animation end
  46977. * @returns the animatable created for this animation
  46978. */
  46979. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46980. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46981. if (!animation) {
  46982. return null;
  46983. }
  46984. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46985. };
  46986. /**
  46987. * Create and start an animation on a node and its descendants
  46988. * @param {string} name defines the name of the global animation that will be run on all nodes
  46989. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46990. * @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.
  46991. * @param {string} targetProperty defines property to animate
  46992. * @param {number} framePerSecond defines the number of frame per second yo use
  46993. * @param {number} totalFrame defines the number of frames in total
  46994. * @param {any} from defines the initial value
  46995. * @param {any} to defines the final value
  46996. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46997. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46998. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46999. * @returns the list of animatables created for all nodes
  47000. * @example https://www.babylonjs-playground.com/#MH0VLI
  47001. */
  47002. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47003. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47004. if (!animation) {
  47005. return null;
  47006. }
  47007. var scene = node.getScene();
  47008. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47009. };
  47010. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47011. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47012. if (!animation) {
  47013. return null;
  47014. }
  47015. node.animations.push(animation);
  47016. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47017. };
  47018. /**
  47019. * Transition property of the Camera to the target Value.
  47020. * @param property The property to transition
  47021. * @param targetValue The target Value of the property
  47022. * @param host The object where the property to animate belongs
  47023. * @param scene Scene used to run the animation
  47024. * @param frameRate Framerate (in frame/s) to use
  47025. * @param transition The transition type we want to use
  47026. * @param duration The duration of the animation, in milliseconds
  47027. * @param onAnimationEnd Call back trigger at the end of the animation.
  47028. */
  47029. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47030. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47031. if (duration <= 0) {
  47032. host[property] = targetValue;
  47033. if (onAnimationEnd) {
  47034. onAnimationEnd();
  47035. }
  47036. return null;
  47037. }
  47038. var endFrame = frameRate * (duration / 1000);
  47039. transition.setKeys([{
  47040. frame: 0,
  47041. value: host[property].clone ? host[property].clone() : host[property]
  47042. },
  47043. {
  47044. frame: endFrame,
  47045. value: targetValue
  47046. }]);
  47047. if (!host.animations) {
  47048. host.animations = [];
  47049. }
  47050. host.animations.push(transition);
  47051. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47052. animation.onAnimationEnd = onAnimationEnd;
  47053. return animation;
  47054. };
  47055. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47056. /**
  47057. * Return the array of runtime animations currently using this animation
  47058. */
  47059. get: function () {
  47060. return this._runtimeAnimations;
  47061. },
  47062. enumerable: true,
  47063. configurable: true
  47064. });
  47065. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47066. get: function () {
  47067. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47068. var runtimeAnimation = _a[_i];
  47069. if (!runtimeAnimation.isStopped) {
  47070. return true;
  47071. }
  47072. }
  47073. return false;
  47074. },
  47075. enumerable: true,
  47076. configurable: true
  47077. });
  47078. // Methods
  47079. /**
  47080. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47081. */
  47082. Animation.prototype.toString = function (fullDetails) {
  47083. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47084. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47085. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47086. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47087. if (fullDetails) {
  47088. ret += ", Ranges: {";
  47089. var first = true;
  47090. for (var name in this._ranges) {
  47091. if (first) {
  47092. ret += ", ";
  47093. first = false;
  47094. }
  47095. ret += name;
  47096. }
  47097. ret += "}";
  47098. }
  47099. return ret;
  47100. };
  47101. /**
  47102. * Add an event to this animation.
  47103. */
  47104. Animation.prototype.addEvent = function (event) {
  47105. this._events.push(event);
  47106. };
  47107. /**
  47108. * Remove all events found at the given frame
  47109. * @param frame
  47110. */
  47111. Animation.prototype.removeEvents = function (frame) {
  47112. for (var index = 0; index < this._events.length; index++) {
  47113. if (this._events[index].frame === frame) {
  47114. this._events.splice(index, 1);
  47115. index--;
  47116. }
  47117. }
  47118. };
  47119. Animation.prototype.getEvents = function () {
  47120. return this._events;
  47121. };
  47122. Animation.prototype.createRange = function (name, from, to) {
  47123. // check name not already in use; could happen for bones after serialized
  47124. if (!this._ranges[name]) {
  47125. this._ranges[name] = new AnimationRange(name, from, to);
  47126. }
  47127. };
  47128. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47129. if (deleteFrames === void 0) { deleteFrames = true; }
  47130. var range = this._ranges[name];
  47131. if (!range) {
  47132. return;
  47133. }
  47134. if (deleteFrames) {
  47135. var from = range.from;
  47136. var to = range.to;
  47137. // this loop MUST go high to low for multiple splices to work
  47138. for (var key = this._keys.length - 1; key >= 0; key--) {
  47139. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47140. this._keys.splice(key, 1);
  47141. }
  47142. }
  47143. }
  47144. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47145. };
  47146. Animation.prototype.getRange = function (name) {
  47147. return this._ranges[name];
  47148. };
  47149. Animation.prototype.getKeys = function () {
  47150. return this._keys;
  47151. };
  47152. Animation.prototype.getHighestFrame = function () {
  47153. var ret = 0;
  47154. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47155. if (ret < this._keys[key].frame) {
  47156. ret = this._keys[key].frame;
  47157. }
  47158. }
  47159. return ret;
  47160. };
  47161. Animation.prototype.getEasingFunction = function () {
  47162. return this._easingFunction;
  47163. };
  47164. Animation.prototype.setEasingFunction = function (easingFunction) {
  47165. this._easingFunction = easingFunction;
  47166. };
  47167. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47168. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47169. };
  47170. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47171. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47172. };
  47173. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47174. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47175. };
  47176. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47177. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47178. };
  47179. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47180. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47181. };
  47182. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47183. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47184. };
  47185. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47186. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47187. };
  47188. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47189. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47190. };
  47191. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47192. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47193. };
  47194. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47195. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47196. };
  47197. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47198. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47199. };
  47200. Animation.prototype.clone = function () {
  47201. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47202. clone.enableBlending = this.enableBlending;
  47203. clone.blendingSpeed = this.blendingSpeed;
  47204. if (this._keys) {
  47205. clone.setKeys(this._keys);
  47206. }
  47207. if (this._ranges) {
  47208. clone._ranges = {};
  47209. for (var name in this._ranges) {
  47210. var range = this._ranges[name];
  47211. if (!range) {
  47212. continue;
  47213. }
  47214. clone._ranges[name] = range.clone();
  47215. }
  47216. }
  47217. return clone;
  47218. };
  47219. Animation.prototype.setKeys = function (values) {
  47220. this._keys = values.slice(0);
  47221. };
  47222. Animation.prototype.serialize = function () {
  47223. var serializationObject = {};
  47224. serializationObject.name = this.name;
  47225. serializationObject.property = this.targetProperty;
  47226. serializationObject.framePerSecond = this.framePerSecond;
  47227. serializationObject.dataType = this.dataType;
  47228. serializationObject.loopBehavior = this.loopMode;
  47229. serializationObject.enableBlending = this.enableBlending;
  47230. serializationObject.blendingSpeed = this.blendingSpeed;
  47231. var dataType = this.dataType;
  47232. serializationObject.keys = [];
  47233. var keys = this.getKeys();
  47234. for (var index = 0; index < keys.length; index++) {
  47235. var animationKey = keys[index];
  47236. var key = {};
  47237. key.frame = animationKey.frame;
  47238. switch (dataType) {
  47239. case Animation.ANIMATIONTYPE_FLOAT:
  47240. key.values = [animationKey.value];
  47241. break;
  47242. case Animation.ANIMATIONTYPE_QUATERNION:
  47243. case Animation.ANIMATIONTYPE_MATRIX:
  47244. case Animation.ANIMATIONTYPE_VECTOR3:
  47245. case Animation.ANIMATIONTYPE_COLOR3:
  47246. key.values = animationKey.value.asArray();
  47247. break;
  47248. }
  47249. serializationObject.keys.push(key);
  47250. }
  47251. serializationObject.ranges = [];
  47252. for (var name in this._ranges) {
  47253. var source = this._ranges[name];
  47254. if (!source) {
  47255. continue;
  47256. }
  47257. var range = {};
  47258. range.name = name;
  47259. range.from = source.from;
  47260. range.to = source.to;
  47261. serializationObject.ranges.push(range);
  47262. }
  47263. return serializationObject;
  47264. };
  47265. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47266. get: function () {
  47267. return Animation._ANIMATIONTYPE_FLOAT;
  47268. },
  47269. enumerable: true,
  47270. configurable: true
  47271. });
  47272. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47273. get: function () {
  47274. return Animation._ANIMATIONTYPE_VECTOR3;
  47275. },
  47276. enumerable: true,
  47277. configurable: true
  47278. });
  47279. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47280. get: function () {
  47281. return Animation._ANIMATIONTYPE_VECTOR2;
  47282. },
  47283. enumerable: true,
  47284. configurable: true
  47285. });
  47286. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47287. get: function () {
  47288. return Animation._ANIMATIONTYPE_SIZE;
  47289. },
  47290. enumerable: true,
  47291. configurable: true
  47292. });
  47293. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47294. get: function () {
  47295. return Animation._ANIMATIONTYPE_QUATERNION;
  47296. },
  47297. enumerable: true,
  47298. configurable: true
  47299. });
  47300. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47301. get: function () {
  47302. return Animation._ANIMATIONTYPE_MATRIX;
  47303. },
  47304. enumerable: true,
  47305. configurable: true
  47306. });
  47307. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47308. get: function () {
  47309. return Animation._ANIMATIONTYPE_COLOR3;
  47310. },
  47311. enumerable: true,
  47312. configurable: true
  47313. });
  47314. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47315. get: function () {
  47316. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47317. },
  47318. enumerable: true,
  47319. configurable: true
  47320. });
  47321. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47322. get: function () {
  47323. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47324. },
  47325. enumerable: true,
  47326. configurable: true
  47327. });
  47328. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47329. get: function () {
  47330. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47331. },
  47332. enumerable: true,
  47333. configurable: true
  47334. });
  47335. Animation.Parse = function (parsedAnimation) {
  47336. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47337. var dataType = parsedAnimation.dataType;
  47338. var keys = [];
  47339. var data;
  47340. var index;
  47341. if (parsedAnimation.enableBlending) {
  47342. animation.enableBlending = parsedAnimation.enableBlending;
  47343. }
  47344. if (parsedAnimation.blendingSpeed) {
  47345. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47346. }
  47347. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47348. var key = parsedAnimation.keys[index];
  47349. var inTangent;
  47350. var outTangent;
  47351. switch (dataType) {
  47352. case Animation.ANIMATIONTYPE_FLOAT:
  47353. data = key.values[0];
  47354. if (key.values.length >= 1) {
  47355. inTangent = key.values[1];
  47356. }
  47357. if (key.values.length >= 2) {
  47358. outTangent = key.values[2];
  47359. }
  47360. break;
  47361. case Animation.ANIMATIONTYPE_QUATERNION:
  47362. data = BABYLON.Quaternion.FromArray(key.values);
  47363. if (key.values.length >= 8) {
  47364. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47365. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47366. inTangent = _inTangent;
  47367. }
  47368. }
  47369. if (key.values.length >= 12) {
  47370. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47371. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47372. outTangent = _outTangent;
  47373. }
  47374. }
  47375. break;
  47376. case Animation.ANIMATIONTYPE_MATRIX:
  47377. data = BABYLON.Matrix.FromArray(key.values);
  47378. break;
  47379. case Animation.ANIMATIONTYPE_COLOR3:
  47380. data = BABYLON.Color3.FromArray(key.values);
  47381. break;
  47382. case Animation.ANIMATIONTYPE_VECTOR3:
  47383. default:
  47384. data = BABYLON.Vector3.FromArray(key.values);
  47385. break;
  47386. }
  47387. var keyData = {};
  47388. keyData.frame = key.frame;
  47389. keyData.value = data;
  47390. if (inTangent != undefined) {
  47391. keyData.inTangent = inTangent;
  47392. }
  47393. if (outTangent != undefined) {
  47394. keyData.outTangent = outTangent;
  47395. }
  47396. keys.push(keyData);
  47397. }
  47398. animation.setKeys(keys);
  47399. if (parsedAnimation.ranges) {
  47400. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47401. data = parsedAnimation.ranges[index];
  47402. animation.createRange(data.name, data.from, data.to);
  47403. }
  47404. }
  47405. return animation;
  47406. };
  47407. Animation.AppendSerializedAnimations = function (source, destination) {
  47408. if (source.animations) {
  47409. destination.animations = [];
  47410. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47411. var animation = source.animations[animationIndex];
  47412. destination.animations.push(animation.serialize());
  47413. }
  47414. }
  47415. };
  47416. Animation.AllowMatricesInterpolation = false;
  47417. // Statics
  47418. Animation._ANIMATIONTYPE_FLOAT = 0;
  47419. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47420. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47421. Animation._ANIMATIONTYPE_MATRIX = 3;
  47422. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47423. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47424. Animation._ANIMATIONTYPE_SIZE = 6;
  47425. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47426. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47427. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47428. return Animation;
  47429. }());
  47430. BABYLON.Animation = Animation;
  47431. })(BABYLON || (BABYLON = {}));
  47432. //# sourceMappingURL=babylon.animation.js.map
  47433. "use strict";
  47434. var BABYLON;
  47435. (function (BABYLON) {
  47436. /**
  47437. * This class defines the direct association between an animation and a target
  47438. */
  47439. var TargetedAnimation = /** @class */ (function () {
  47440. function TargetedAnimation() {
  47441. }
  47442. return TargetedAnimation;
  47443. }());
  47444. BABYLON.TargetedAnimation = TargetedAnimation;
  47445. /**
  47446. * Use this class to create coordinated animations on multiple targets
  47447. */
  47448. var AnimationGroup = /** @class */ (function () {
  47449. function AnimationGroup(name, scene) {
  47450. if (scene === void 0) { scene = null; }
  47451. this.name = name;
  47452. this._targetedAnimations = new Array();
  47453. this._animatables = new Array();
  47454. this._from = Number.MAX_VALUE;
  47455. this._to = -Number.MAX_VALUE;
  47456. this._speedRatio = 1;
  47457. this.onAnimationEndObservable = new BABYLON.Observable();
  47458. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47459. this._scene.animationGroups.push(this);
  47460. }
  47461. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47462. /**
  47463. * Define if the animations are started
  47464. */
  47465. get: function () {
  47466. return this._isStarted;
  47467. },
  47468. enumerable: true,
  47469. configurable: true
  47470. });
  47471. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47472. /**
  47473. * Gets or sets the speed ratio to use for all animations
  47474. */
  47475. get: function () {
  47476. return this._speedRatio;
  47477. },
  47478. /**
  47479. * Gets or sets the speed ratio to use for all animations
  47480. */
  47481. set: function (value) {
  47482. if (this._speedRatio === value) {
  47483. return;
  47484. }
  47485. this._speedRatio = value;
  47486. for (var index = 0; index < this._animatables.length; index++) {
  47487. var animatable = this._animatables[index];
  47488. animatable.speedRatio = this._speedRatio;
  47489. }
  47490. },
  47491. enumerable: true,
  47492. configurable: true
  47493. });
  47494. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47495. /**
  47496. * Gets the targeted animations for this animation group
  47497. */
  47498. get: function () {
  47499. return this._targetedAnimations;
  47500. },
  47501. enumerable: true,
  47502. configurable: true
  47503. });
  47504. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47505. /**
  47506. * returning the list of animatables controlled by this animation group.
  47507. */
  47508. get: function () {
  47509. return this._animatables;
  47510. },
  47511. enumerable: true,
  47512. configurable: true
  47513. });
  47514. /**
  47515. * Add an animation (with its target) in the group
  47516. * @param animation defines the animation we want to add
  47517. * @param target defines the target of the animation
  47518. * @returns the {BABYLON.TargetedAnimation} object
  47519. */
  47520. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47521. var targetedAnimation = {
  47522. animation: animation,
  47523. target: target
  47524. };
  47525. var keys = animation.getKeys();
  47526. if (this._from > keys[0].frame) {
  47527. this._from = keys[0].frame;
  47528. }
  47529. if (this._to < keys[keys.length - 1].frame) {
  47530. this._to = keys[keys.length - 1].frame;
  47531. }
  47532. this._targetedAnimations.push(targetedAnimation);
  47533. return targetedAnimation;
  47534. };
  47535. /**
  47536. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47537. * It can add constant keys at begin or end
  47538. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47539. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47540. */
  47541. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47542. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47543. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47544. beginFrame = Math.max(beginFrame, this._from);
  47545. endFrame = Math.min(endFrame, this._to);
  47546. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47547. var targetedAnimation = this._targetedAnimations[index];
  47548. var keys = targetedAnimation.animation.getKeys();
  47549. var startKey = keys[0];
  47550. var endKey = keys[keys.length - 1];
  47551. if (startKey.frame > beginFrame) {
  47552. var newKey = {
  47553. frame: beginFrame,
  47554. value: startKey.value,
  47555. inTangent: startKey.inTangent,
  47556. outTangent: startKey.outTangent,
  47557. interpolation: startKey.interpolation
  47558. };
  47559. keys.splice(0, 0, newKey);
  47560. }
  47561. if (endKey.frame < endFrame) {
  47562. var newKey = {
  47563. frame: endFrame,
  47564. value: endKey.value,
  47565. inTangent: endKey.outTangent,
  47566. outTangent: endKey.outTangent,
  47567. interpolation: endKey.interpolation
  47568. };
  47569. keys.push(newKey);
  47570. }
  47571. }
  47572. return this;
  47573. };
  47574. /**
  47575. * Start all animations on given targets
  47576. * @param loop defines if animations must loop
  47577. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47578. */
  47579. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47580. var _this = this;
  47581. if (loop === void 0) { loop = false; }
  47582. if (speedRatio === void 0) { speedRatio = 1; }
  47583. if (this._isStarted || this._targetedAnimations.length === 0) {
  47584. return this;
  47585. }
  47586. var _loop_1 = function () {
  47587. var targetedAnimation = this_1._targetedAnimations[index];
  47588. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47589. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47590. }));
  47591. };
  47592. var this_1 = this;
  47593. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47594. _loop_1();
  47595. }
  47596. this._speedRatio = speedRatio;
  47597. this._isStarted = true;
  47598. return this;
  47599. };
  47600. /**
  47601. * Pause all animations
  47602. */
  47603. AnimationGroup.prototype.pause = function () {
  47604. if (!this._isStarted) {
  47605. return this;
  47606. }
  47607. for (var index = 0; index < this._animatables.length; index++) {
  47608. var animatable = this._animatables[index];
  47609. animatable.pause();
  47610. }
  47611. return this;
  47612. };
  47613. /**
  47614. * Play all animations to initial state
  47615. * This function will start() the animations if they were not started or will restart() them if they were paused
  47616. * @param loop defines if animations must loop
  47617. */
  47618. AnimationGroup.prototype.play = function (loop) {
  47619. if (this.isStarted) {
  47620. if (loop !== undefined) {
  47621. for (var index = 0; index < this._animatables.length; index++) {
  47622. var animatable = this._animatables[index];
  47623. animatable.loopAnimation = loop;
  47624. }
  47625. }
  47626. this.restart();
  47627. }
  47628. else {
  47629. this.start(loop, this._speedRatio);
  47630. }
  47631. return this;
  47632. };
  47633. /**
  47634. * Reset all animations to initial state
  47635. */
  47636. AnimationGroup.prototype.reset = function () {
  47637. if (!this._isStarted) {
  47638. return this;
  47639. }
  47640. for (var index = 0; index < this._animatables.length; index++) {
  47641. var animatable = this._animatables[index];
  47642. animatable.reset();
  47643. }
  47644. return this;
  47645. };
  47646. /**
  47647. * Restart animations from key 0
  47648. */
  47649. AnimationGroup.prototype.restart = function () {
  47650. if (!this._isStarted) {
  47651. return this;
  47652. }
  47653. for (var index = 0; index < this._animatables.length; index++) {
  47654. var animatable = this._animatables[index];
  47655. animatable.restart();
  47656. }
  47657. return this;
  47658. };
  47659. /**
  47660. * Stop all animations
  47661. */
  47662. AnimationGroup.prototype.stop = function () {
  47663. if (!this._isStarted) {
  47664. return this;
  47665. }
  47666. for (var index = 0; index < this._animatables.length; index++) {
  47667. var animatable = this._animatables[index];
  47668. animatable.stop();
  47669. }
  47670. this._isStarted = false;
  47671. return this;
  47672. };
  47673. /**
  47674. * Goes to a specific frame in this animation group
  47675. *
  47676. * @param frame the frame number to go to
  47677. * @return the animationGroup
  47678. */
  47679. AnimationGroup.prototype.goToFrame = function (frame) {
  47680. if (!this._isStarted) {
  47681. return this;
  47682. }
  47683. for (var index = 0; index < this._animatables.length; index++) {
  47684. var animatable = this._animatables[index];
  47685. animatable.goToFrame(frame);
  47686. }
  47687. return this;
  47688. };
  47689. /**
  47690. * Dispose all associated resources
  47691. */
  47692. AnimationGroup.prototype.dispose = function () {
  47693. this._targetedAnimations = [];
  47694. this._animatables = [];
  47695. var index = this._scene.animationGroups.indexOf(this);
  47696. if (index > -1) {
  47697. this._scene.animationGroups.splice(index, 1);
  47698. }
  47699. };
  47700. return AnimationGroup;
  47701. }());
  47702. BABYLON.AnimationGroup = AnimationGroup;
  47703. })(BABYLON || (BABYLON = {}));
  47704. //# sourceMappingURL=babylon.animationGroup.js.map
  47705. "use strict";
  47706. var BABYLON;
  47707. (function (BABYLON) {
  47708. var RuntimeAnimation = /** @class */ (function () {
  47709. /**
  47710. * Create a new RuntimeAnimation object
  47711. * @param target defines the target of the animation
  47712. * @param animation defines the source {BABYLON.Animation} object
  47713. * @param scene defines the hosting scene
  47714. */
  47715. function RuntimeAnimation(target, animation, scene) {
  47716. this.currentFrame = 0;
  47717. this._offsetsCache = {};
  47718. this._highLimitsCache = {};
  47719. this._stopped = false;
  47720. this._blendingFactor = 0;
  47721. this._targetPath = "";
  47722. this._weight = 1.0;
  47723. this._ratioOffset = 0;
  47724. this._previousDelay = 0;
  47725. this._previousRatio = 0;
  47726. this._animation = animation;
  47727. this._target = target;
  47728. this._scene = scene;
  47729. animation._runtimeAnimations.push(this);
  47730. }
  47731. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47732. /**
  47733. * Gets the weight of the runtime animation
  47734. */
  47735. get: function () {
  47736. return this._weight;
  47737. },
  47738. enumerable: true,
  47739. configurable: true
  47740. });
  47741. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47742. /**
  47743. * Gets the original value of the runtime animation
  47744. */
  47745. get: function () {
  47746. return this._originalValue;
  47747. },
  47748. enumerable: true,
  47749. configurable: true
  47750. });
  47751. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47752. /**
  47753. * Gets the current value of the runtime animation
  47754. */
  47755. get: function () {
  47756. return this._currentValue;
  47757. },
  47758. enumerable: true,
  47759. configurable: true
  47760. });
  47761. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47762. /**
  47763. * Gets the path where to store the animated value in the target
  47764. */
  47765. get: function () {
  47766. return this._targetPath;
  47767. },
  47768. enumerable: true,
  47769. configurable: true
  47770. });
  47771. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47772. /**
  47773. * Gets the actual target of the runtime animation
  47774. */
  47775. get: function () {
  47776. return this._activeTarget;
  47777. },
  47778. enumerable: true,
  47779. configurable: true
  47780. });
  47781. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47782. get: function () {
  47783. return this._animation;
  47784. },
  47785. enumerable: true,
  47786. configurable: true
  47787. });
  47788. RuntimeAnimation.prototype.reset = function () {
  47789. this._offsetsCache = {};
  47790. this._highLimitsCache = {};
  47791. this.currentFrame = 0;
  47792. this._blendingFactor = 0;
  47793. this._originalValue = null;
  47794. };
  47795. RuntimeAnimation.prototype.isStopped = function () {
  47796. return this._stopped;
  47797. };
  47798. RuntimeAnimation.prototype.dispose = function () {
  47799. var index = this._animation.runtimeAnimations.indexOf(this);
  47800. if (index > -1) {
  47801. this._animation.runtimeAnimations.splice(index, 1);
  47802. }
  47803. };
  47804. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47805. if (typeof value === "function") {
  47806. return value();
  47807. }
  47808. return value;
  47809. };
  47810. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47811. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47812. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47813. }
  47814. this.currentFrame = currentFrame;
  47815. var keys = this._animation.getKeys();
  47816. // Try to get a hash to find the right key
  47817. 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));
  47818. if (keys[startKeyIndex].frame >= currentFrame) {
  47819. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47820. startKeyIndex--;
  47821. }
  47822. }
  47823. for (var key = startKeyIndex; key < keys.length; key++) {
  47824. var endKey = keys[key + 1];
  47825. if (endKey.frame >= currentFrame) {
  47826. var startKey = keys[key];
  47827. var startValue = this._getKeyValue(startKey.value);
  47828. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47829. return startValue;
  47830. }
  47831. var endValue = this._getKeyValue(endKey.value);
  47832. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47833. var frameDelta = endKey.frame - startKey.frame;
  47834. // gradient : percent of currentFrame between the frame inf and the frame sup
  47835. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47836. // check for easingFunction and correction of gradient
  47837. var easingFunction = this._animation.getEasingFunction();
  47838. if (easingFunction != null) {
  47839. gradient = easingFunction.ease(gradient);
  47840. }
  47841. switch (this._animation.dataType) {
  47842. // Float
  47843. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47844. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47845. switch (loopMode) {
  47846. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47847. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47848. return floatValue;
  47849. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47850. return offsetValue * repeatCount + floatValue;
  47851. }
  47852. break;
  47853. // Quaternion
  47854. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47855. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47856. switch (loopMode) {
  47857. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47858. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47859. return quatValue;
  47860. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47861. return quatValue.add(offsetValue.scale(repeatCount));
  47862. }
  47863. return quatValue;
  47864. // Vector3
  47865. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47866. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47867. switch (loopMode) {
  47868. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47869. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47870. return vec3Value;
  47871. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47872. return vec3Value.add(offsetValue.scale(repeatCount));
  47873. }
  47874. // Vector2
  47875. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47876. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47877. switch (loopMode) {
  47878. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47879. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47880. return vec2Value;
  47881. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47882. return vec2Value.add(offsetValue.scale(repeatCount));
  47883. }
  47884. // Size
  47885. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47886. switch (loopMode) {
  47887. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47888. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47889. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47890. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47891. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47892. }
  47893. // Color3
  47894. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47895. switch (loopMode) {
  47896. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47897. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47898. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47899. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47900. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47901. }
  47902. // Matrix
  47903. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47904. switch (loopMode) {
  47905. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47906. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47907. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47908. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47909. }
  47910. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47911. return startValue;
  47912. }
  47913. default:
  47914. break;
  47915. }
  47916. break;
  47917. }
  47918. }
  47919. return this._getKeyValue(keys[keys.length - 1].value);
  47920. };
  47921. /**
  47922. * Affect the interpolated value to the target
  47923. * @param currentValue defines the value computed by the animation
  47924. * @param weight defines the weight to apply to this value
  47925. */
  47926. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47927. if (weight === void 0) { weight = 1.0; }
  47928. // Set value
  47929. var path;
  47930. var destination;
  47931. var targetPropertyPath = this._animation.targetPropertyPath;
  47932. if (targetPropertyPath.length > 1) {
  47933. var property = this._target[targetPropertyPath[0]];
  47934. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47935. property = property[targetPropertyPath[index]];
  47936. }
  47937. path = targetPropertyPath[targetPropertyPath.length - 1];
  47938. destination = property;
  47939. }
  47940. else {
  47941. path = targetPropertyPath[0];
  47942. destination = this._target;
  47943. }
  47944. this._targetPath = path;
  47945. this._activeTarget = destination;
  47946. this._weight = weight;
  47947. // Blending
  47948. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47949. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47950. if (enableBlending && this._blendingFactor <= 1.0) {
  47951. if (!this._originalBlendValue) {
  47952. var originalValue = destination[path];
  47953. if (originalValue.clone) {
  47954. this._originalBlendValue = originalValue.clone();
  47955. }
  47956. else {
  47957. this._originalBlendValue = originalValue;
  47958. }
  47959. }
  47960. }
  47961. if (weight !== -1.0) {
  47962. if (!this._originalValue) {
  47963. var originalValue = void 0;
  47964. if (destination.getRestPose) {
  47965. originalValue = destination.getRestPose();
  47966. }
  47967. else {
  47968. originalValue = destination[path];
  47969. }
  47970. if (originalValue.clone) {
  47971. this._originalValue = originalValue.clone();
  47972. }
  47973. else {
  47974. this._originalValue = originalValue;
  47975. }
  47976. }
  47977. }
  47978. if (enableBlending && this._blendingFactor <= 1.0) {
  47979. if (this._originalBlendValue.prototype) {
  47980. if (this._originalBlendValue.prototype.Lerp) {
  47981. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47982. }
  47983. else {
  47984. this._currentValue = currentValue;
  47985. }
  47986. }
  47987. else if (this._originalBlendValue.m) {
  47988. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47989. }
  47990. else {
  47991. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47992. }
  47993. this._blendingFactor += blendingSpeed;
  47994. }
  47995. else {
  47996. this._currentValue = currentValue;
  47997. }
  47998. if (weight !== -1.0) {
  47999. this._scene._registerTargetForLateAnimationBinding(this);
  48000. }
  48001. else {
  48002. destination[path] = this._currentValue;
  48003. }
  48004. if (this._target.markAsDirty) {
  48005. this._target.markAsDirty(this._animation.targetProperty);
  48006. }
  48007. };
  48008. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  48009. if (this._target && this._target.animationPropertiesOverride) {
  48010. return this._target.animationPropertiesOverride.loopMode;
  48011. }
  48012. return this._animation.loopMode;
  48013. };
  48014. /**
  48015. * Move the current animation to a given frame
  48016. * @param frame defines the frame to move to
  48017. */
  48018. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48019. var keys = this._animation.getKeys();
  48020. if (frame < keys[0].frame) {
  48021. frame = keys[0].frame;
  48022. }
  48023. else if (frame > keys[keys.length - 1].frame) {
  48024. frame = keys[keys.length - 1].frame;
  48025. }
  48026. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  48027. this.setValue(currentValue, -1);
  48028. };
  48029. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  48030. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  48031. this._ratioOffset = this._previousRatio - newRatio;
  48032. };
  48033. /**
  48034. * Execute the current animation
  48035. * @param delay defines the delay to add to the current frame
  48036. * @param from defines the lower bound of the animation range
  48037. * @param to defines the upper bound of the animation range
  48038. * @param loop defines if the current animation must loop
  48039. * @param speedRatio defines the current speed ratio
  48040. * @param weight defines the weight of the animation (default is -1 so no weight)
  48041. * @returns a boolean indicating if the animation has ended
  48042. */
  48043. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48044. if (weight === void 0) { weight = -1.0; }
  48045. var targetPropertyPath = this._animation.targetPropertyPath;
  48046. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48047. this._stopped = true;
  48048. return false;
  48049. }
  48050. var returnValue = true;
  48051. var keys = this._animation.getKeys();
  48052. // Adding a start key at frame 0 if missing
  48053. if (keys[0].frame !== 0) {
  48054. var newKey = { frame: 0, value: keys[0].value };
  48055. keys.splice(0, 0, newKey);
  48056. }
  48057. // Check limits
  48058. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48059. from = keys[0].frame;
  48060. }
  48061. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48062. to = keys[keys.length - 1].frame;
  48063. }
  48064. //to and from cannot be the same key
  48065. if (from === to) {
  48066. if (from > keys[0].frame) {
  48067. from--;
  48068. }
  48069. else if (to < keys[keys.length - 1].frame) {
  48070. to++;
  48071. }
  48072. }
  48073. // Compute ratio
  48074. var range = to - from;
  48075. var offsetValue;
  48076. // ratio represents the frame delta between from and to
  48077. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48078. var highLimitValue = 0;
  48079. this._previousDelay = delay;
  48080. this._previousRatio = ratio;
  48081. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48082. returnValue = false;
  48083. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48084. }
  48085. else {
  48086. // Get max value if required
  48087. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48088. var keyOffset = to.toString() + from.toString();
  48089. if (!this._offsetsCache[keyOffset]) {
  48090. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48091. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48092. switch (this._animation.dataType) {
  48093. // Float
  48094. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48095. this._offsetsCache[keyOffset] = toValue - fromValue;
  48096. break;
  48097. // Quaternion
  48098. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48099. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48100. break;
  48101. // Vector3
  48102. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48103. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48104. // Vector2
  48105. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48106. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48107. // Size
  48108. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48109. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48110. // Color3
  48111. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48112. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48113. default:
  48114. break;
  48115. }
  48116. this._highLimitsCache[keyOffset] = toValue;
  48117. }
  48118. highLimitValue = this._highLimitsCache[keyOffset];
  48119. offsetValue = this._offsetsCache[keyOffset];
  48120. }
  48121. }
  48122. if (offsetValue === undefined) {
  48123. switch (this._animation.dataType) {
  48124. // Float
  48125. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48126. offsetValue = 0;
  48127. break;
  48128. // Quaternion
  48129. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48130. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48131. break;
  48132. // Vector3
  48133. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48134. offsetValue = BABYLON.Vector3.Zero();
  48135. break;
  48136. // Vector2
  48137. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48138. offsetValue = BABYLON.Vector2.Zero();
  48139. break;
  48140. // Size
  48141. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48142. offsetValue = BABYLON.Size.Zero();
  48143. break;
  48144. // Color3
  48145. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48146. offsetValue = BABYLON.Color3.Black();
  48147. }
  48148. }
  48149. // Compute value
  48150. var repeatCount = (ratio / range) >> 0;
  48151. var currentFrame = returnValue ? from + ratio % range : to;
  48152. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48153. // Set value
  48154. this.setValue(currentValue, weight);
  48155. // Check events
  48156. var events = this._animation.getEvents();
  48157. for (var index = 0; index < events.length; index++) {
  48158. // Make sure current frame has passed event frame and that event frame is within the current range
  48159. // Also, handle both forward and reverse animations
  48160. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48161. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48162. var event = events[index];
  48163. if (!event.isDone) {
  48164. // If event should be done only once, remove it.
  48165. if (event.onlyOnce) {
  48166. events.splice(index, 1);
  48167. index--;
  48168. }
  48169. event.isDone = true;
  48170. event.action();
  48171. } // Don't do anything if the event has already be done.
  48172. }
  48173. else if (events[index].isDone && !events[index].onlyOnce) {
  48174. // reset event, the animation is looping
  48175. events[index].isDone = false;
  48176. }
  48177. }
  48178. if (!returnValue) {
  48179. this._stopped = true;
  48180. }
  48181. return returnValue;
  48182. };
  48183. return RuntimeAnimation;
  48184. }());
  48185. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48186. })(BABYLON || (BABYLON = {}));
  48187. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48188. "use strict";
  48189. var BABYLON;
  48190. (function (BABYLON) {
  48191. var Animatable = /** @class */ (function () {
  48192. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48193. if (fromFrame === void 0) { fromFrame = 0; }
  48194. if (toFrame === void 0) { toFrame = 100; }
  48195. if (loopAnimation === void 0) { loopAnimation = false; }
  48196. if (speedRatio === void 0) { speedRatio = 1.0; }
  48197. this.target = target;
  48198. this.fromFrame = fromFrame;
  48199. this.toFrame = toFrame;
  48200. this.loopAnimation = loopAnimation;
  48201. this.onAnimationEnd = onAnimationEnd;
  48202. this._localDelayOffset = null;
  48203. this._pausedDelay = null;
  48204. this._runtimeAnimations = new Array();
  48205. this._paused = false;
  48206. this._speedRatio = 1;
  48207. this._weight = -1.0;
  48208. this.animationStarted = false;
  48209. if (animations) {
  48210. this.appendAnimations(target, animations);
  48211. }
  48212. this._speedRatio = speedRatio;
  48213. this._scene = scene;
  48214. scene._activeAnimatables.push(this);
  48215. }
  48216. Object.defineProperty(Animatable.prototype, "weight", {
  48217. /**
  48218. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48219. */
  48220. get: function () {
  48221. return this._weight;
  48222. },
  48223. set: function (value) {
  48224. if (value === -1) {
  48225. this._weight = -1;
  48226. return;
  48227. }
  48228. // Else weight must be in [0, 1] range
  48229. this._weight = Math.min(Math.max(value, 0), 1.0);
  48230. },
  48231. enumerable: true,
  48232. configurable: true
  48233. });
  48234. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48235. /**
  48236. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48237. */
  48238. get: function () {
  48239. return this._speedRatio;
  48240. },
  48241. set: function (value) {
  48242. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48243. var animation = this._runtimeAnimations[index];
  48244. animation._prepareForSpeedRatioChange(value);
  48245. }
  48246. this._speedRatio = value;
  48247. },
  48248. enumerable: true,
  48249. configurable: true
  48250. });
  48251. // Methods
  48252. Animatable.prototype.getAnimations = function () {
  48253. return this._runtimeAnimations;
  48254. };
  48255. Animatable.prototype.appendAnimations = function (target, animations) {
  48256. for (var index = 0; index < animations.length; index++) {
  48257. var animation = animations[index];
  48258. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene));
  48259. }
  48260. };
  48261. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48262. var runtimeAnimations = this._runtimeAnimations;
  48263. for (var index = 0; index < runtimeAnimations.length; index++) {
  48264. if (runtimeAnimations[index].animation.targetProperty === property) {
  48265. return runtimeAnimations[index].animation;
  48266. }
  48267. }
  48268. return null;
  48269. };
  48270. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48271. var runtimeAnimations = this._runtimeAnimations;
  48272. for (var index = 0; index < runtimeAnimations.length; index++) {
  48273. if (runtimeAnimations[index].animation.targetProperty === property) {
  48274. return runtimeAnimations[index];
  48275. }
  48276. }
  48277. return null;
  48278. };
  48279. Animatable.prototype.reset = function () {
  48280. var runtimeAnimations = this._runtimeAnimations;
  48281. for (var index = 0; index < runtimeAnimations.length; index++) {
  48282. runtimeAnimations[index].reset();
  48283. }
  48284. // Reset to original value
  48285. for (index = 0; index < runtimeAnimations.length; index++) {
  48286. var animation = runtimeAnimations[index];
  48287. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48288. }
  48289. this._localDelayOffset = null;
  48290. this._pausedDelay = null;
  48291. };
  48292. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48293. var runtimeAnimations = this._runtimeAnimations;
  48294. for (var index = 0; index < runtimeAnimations.length; index++) {
  48295. runtimeAnimations[index].animation.enableBlending = true;
  48296. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48297. }
  48298. };
  48299. Animatable.prototype.disableBlending = function () {
  48300. var runtimeAnimations = this._runtimeAnimations;
  48301. for (var index = 0; index < runtimeAnimations.length; index++) {
  48302. runtimeAnimations[index].animation.enableBlending = false;
  48303. }
  48304. };
  48305. Animatable.prototype.goToFrame = function (frame) {
  48306. var runtimeAnimations = this._runtimeAnimations;
  48307. if (runtimeAnimations[0]) {
  48308. var fps = runtimeAnimations[0].animation.framePerSecond;
  48309. var currentFrame = runtimeAnimations[0].currentFrame;
  48310. var adjustTime = frame - currentFrame;
  48311. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48312. if (this._localDelayOffset === null) {
  48313. this._localDelayOffset = 0;
  48314. }
  48315. this._localDelayOffset -= delay;
  48316. }
  48317. for (var index = 0; index < runtimeAnimations.length; index++) {
  48318. runtimeAnimations[index].goToFrame(frame);
  48319. }
  48320. };
  48321. Animatable.prototype.pause = function () {
  48322. if (this._paused) {
  48323. return;
  48324. }
  48325. this._paused = true;
  48326. };
  48327. Animatable.prototype.restart = function () {
  48328. this._paused = false;
  48329. };
  48330. Animatable.prototype.stop = function (animationName) {
  48331. if (animationName) {
  48332. var idx = this._scene._activeAnimatables.indexOf(this);
  48333. if (idx > -1) {
  48334. var runtimeAnimations = this._runtimeAnimations;
  48335. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48336. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48337. continue;
  48338. }
  48339. runtimeAnimations[index].dispose();
  48340. runtimeAnimations.splice(index, 1);
  48341. }
  48342. if (runtimeAnimations.length == 0) {
  48343. this._scene._activeAnimatables.splice(idx, 1);
  48344. if (this.onAnimationEnd) {
  48345. this.onAnimationEnd();
  48346. }
  48347. }
  48348. }
  48349. }
  48350. else {
  48351. var index = this._scene._activeAnimatables.indexOf(this);
  48352. if (index > -1) {
  48353. this._scene._activeAnimatables.splice(index, 1);
  48354. var runtimeAnimations = this._runtimeAnimations;
  48355. for (var index = 0; index < runtimeAnimations.length; index++) {
  48356. runtimeAnimations[index].dispose();
  48357. }
  48358. if (this.onAnimationEnd) {
  48359. this.onAnimationEnd();
  48360. }
  48361. }
  48362. }
  48363. };
  48364. Animatable.prototype._animate = function (delay) {
  48365. if (this._paused) {
  48366. this.animationStarted = false;
  48367. if (this._pausedDelay === null) {
  48368. this._pausedDelay = delay;
  48369. }
  48370. return true;
  48371. }
  48372. if (this._localDelayOffset === null) {
  48373. this._localDelayOffset = delay;
  48374. this._pausedDelay = null;
  48375. }
  48376. else if (this._pausedDelay !== null) {
  48377. this._localDelayOffset += delay - this._pausedDelay;
  48378. this._pausedDelay = null;
  48379. }
  48380. if (this._weight === 0) {
  48381. return true;
  48382. }
  48383. // Animating
  48384. var running = false;
  48385. var runtimeAnimations = this._runtimeAnimations;
  48386. var index;
  48387. for (index = 0; index < runtimeAnimations.length; index++) {
  48388. var animation = runtimeAnimations[index];
  48389. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48390. running = running || isRunning;
  48391. }
  48392. this.animationStarted = running;
  48393. if (!running) {
  48394. // Remove from active animatables
  48395. index = this._scene._activeAnimatables.indexOf(this);
  48396. this._scene._activeAnimatables.splice(index, 1);
  48397. // Dispose all runtime animations
  48398. for (index = 0; index < runtimeAnimations.length; index++) {
  48399. runtimeAnimations[index].dispose();
  48400. }
  48401. }
  48402. if (!running && this.onAnimationEnd) {
  48403. this.onAnimationEnd();
  48404. this.onAnimationEnd = null;
  48405. }
  48406. return running;
  48407. };
  48408. return Animatable;
  48409. }());
  48410. BABYLON.Animatable = Animatable;
  48411. })(BABYLON || (BABYLON = {}));
  48412. //# sourceMappingURL=babylon.animatable.js.map
  48413. "use strict";
  48414. var BABYLON;
  48415. (function (BABYLON) {
  48416. var EasingFunction = /** @class */ (function () {
  48417. function EasingFunction() {
  48418. // Properties
  48419. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48420. }
  48421. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48422. get: function () {
  48423. return EasingFunction._EASINGMODE_EASEIN;
  48424. },
  48425. enumerable: true,
  48426. configurable: true
  48427. });
  48428. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48429. get: function () {
  48430. return EasingFunction._EASINGMODE_EASEOUT;
  48431. },
  48432. enumerable: true,
  48433. configurable: true
  48434. });
  48435. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48436. get: function () {
  48437. return EasingFunction._EASINGMODE_EASEINOUT;
  48438. },
  48439. enumerable: true,
  48440. configurable: true
  48441. });
  48442. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48443. var n = Math.min(Math.max(easingMode, 0), 2);
  48444. this._easingMode = n;
  48445. };
  48446. EasingFunction.prototype.getEasingMode = function () {
  48447. return this._easingMode;
  48448. };
  48449. EasingFunction.prototype.easeInCore = function (gradient) {
  48450. throw new Error('You must implement this method');
  48451. };
  48452. EasingFunction.prototype.ease = function (gradient) {
  48453. switch (this._easingMode) {
  48454. case EasingFunction.EASINGMODE_EASEIN:
  48455. return this.easeInCore(gradient);
  48456. case EasingFunction.EASINGMODE_EASEOUT:
  48457. return (1 - this.easeInCore(1 - gradient));
  48458. }
  48459. if (gradient >= 0.5) {
  48460. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48461. }
  48462. return (this.easeInCore(gradient * 2) * 0.5);
  48463. };
  48464. //Statics
  48465. EasingFunction._EASINGMODE_EASEIN = 0;
  48466. EasingFunction._EASINGMODE_EASEOUT = 1;
  48467. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48468. return EasingFunction;
  48469. }());
  48470. BABYLON.EasingFunction = EasingFunction;
  48471. var CircleEase = /** @class */ (function (_super) {
  48472. __extends(CircleEase, _super);
  48473. function CircleEase() {
  48474. return _super !== null && _super.apply(this, arguments) || this;
  48475. }
  48476. CircleEase.prototype.easeInCore = function (gradient) {
  48477. gradient = Math.max(0, Math.min(1, gradient));
  48478. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48479. };
  48480. return CircleEase;
  48481. }(EasingFunction));
  48482. BABYLON.CircleEase = CircleEase;
  48483. var BackEase = /** @class */ (function (_super) {
  48484. __extends(BackEase, _super);
  48485. function BackEase(amplitude) {
  48486. if (amplitude === void 0) { amplitude = 1; }
  48487. var _this = _super.call(this) || this;
  48488. _this.amplitude = amplitude;
  48489. return _this;
  48490. }
  48491. BackEase.prototype.easeInCore = function (gradient) {
  48492. var num = Math.max(0, this.amplitude);
  48493. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48494. };
  48495. return BackEase;
  48496. }(EasingFunction));
  48497. BABYLON.BackEase = BackEase;
  48498. var BounceEase = /** @class */ (function (_super) {
  48499. __extends(BounceEase, _super);
  48500. function BounceEase(bounces, bounciness) {
  48501. if (bounces === void 0) { bounces = 3; }
  48502. if (bounciness === void 0) { bounciness = 2; }
  48503. var _this = _super.call(this) || this;
  48504. _this.bounces = bounces;
  48505. _this.bounciness = bounciness;
  48506. return _this;
  48507. }
  48508. BounceEase.prototype.easeInCore = function (gradient) {
  48509. var y = Math.max(0.0, this.bounces);
  48510. var bounciness = this.bounciness;
  48511. if (bounciness <= 1.0) {
  48512. bounciness = 1.001;
  48513. }
  48514. var num9 = Math.pow(bounciness, y);
  48515. var num5 = 1.0 - bounciness;
  48516. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48517. var num15 = gradient * num4;
  48518. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48519. var num3 = Math.floor(num65);
  48520. var num13 = num3 + 1.0;
  48521. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48522. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48523. var num7 = (num8 + num12) * 0.5;
  48524. var num6 = gradient - num7;
  48525. var num2 = num7 - num8;
  48526. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48527. };
  48528. return BounceEase;
  48529. }(EasingFunction));
  48530. BABYLON.BounceEase = BounceEase;
  48531. var CubicEase = /** @class */ (function (_super) {
  48532. __extends(CubicEase, _super);
  48533. function CubicEase() {
  48534. return _super !== null && _super.apply(this, arguments) || this;
  48535. }
  48536. CubicEase.prototype.easeInCore = function (gradient) {
  48537. return (gradient * gradient * gradient);
  48538. };
  48539. return CubicEase;
  48540. }(EasingFunction));
  48541. BABYLON.CubicEase = CubicEase;
  48542. var ElasticEase = /** @class */ (function (_super) {
  48543. __extends(ElasticEase, _super);
  48544. function ElasticEase(oscillations, springiness) {
  48545. if (oscillations === void 0) { oscillations = 3; }
  48546. if (springiness === void 0) { springiness = 3; }
  48547. var _this = _super.call(this) || this;
  48548. _this.oscillations = oscillations;
  48549. _this.springiness = springiness;
  48550. return _this;
  48551. }
  48552. ElasticEase.prototype.easeInCore = function (gradient) {
  48553. var num2;
  48554. var num3 = Math.max(0.0, this.oscillations);
  48555. var num = Math.max(0.0, this.springiness);
  48556. if (num == 0) {
  48557. num2 = gradient;
  48558. }
  48559. else {
  48560. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48561. }
  48562. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48563. };
  48564. return ElasticEase;
  48565. }(EasingFunction));
  48566. BABYLON.ElasticEase = ElasticEase;
  48567. var ExponentialEase = /** @class */ (function (_super) {
  48568. __extends(ExponentialEase, _super);
  48569. function ExponentialEase(exponent) {
  48570. if (exponent === void 0) { exponent = 2; }
  48571. var _this = _super.call(this) || this;
  48572. _this.exponent = exponent;
  48573. return _this;
  48574. }
  48575. ExponentialEase.prototype.easeInCore = function (gradient) {
  48576. if (this.exponent <= 0) {
  48577. return gradient;
  48578. }
  48579. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48580. };
  48581. return ExponentialEase;
  48582. }(EasingFunction));
  48583. BABYLON.ExponentialEase = ExponentialEase;
  48584. var PowerEase = /** @class */ (function (_super) {
  48585. __extends(PowerEase, _super);
  48586. function PowerEase(power) {
  48587. if (power === void 0) { power = 2; }
  48588. var _this = _super.call(this) || this;
  48589. _this.power = power;
  48590. return _this;
  48591. }
  48592. PowerEase.prototype.easeInCore = function (gradient) {
  48593. var y = Math.max(0.0, this.power);
  48594. return Math.pow(gradient, y);
  48595. };
  48596. return PowerEase;
  48597. }(EasingFunction));
  48598. BABYLON.PowerEase = PowerEase;
  48599. var QuadraticEase = /** @class */ (function (_super) {
  48600. __extends(QuadraticEase, _super);
  48601. function QuadraticEase() {
  48602. return _super !== null && _super.apply(this, arguments) || this;
  48603. }
  48604. QuadraticEase.prototype.easeInCore = function (gradient) {
  48605. return (gradient * gradient);
  48606. };
  48607. return QuadraticEase;
  48608. }(EasingFunction));
  48609. BABYLON.QuadraticEase = QuadraticEase;
  48610. var QuarticEase = /** @class */ (function (_super) {
  48611. __extends(QuarticEase, _super);
  48612. function QuarticEase() {
  48613. return _super !== null && _super.apply(this, arguments) || this;
  48614. }
  48615. QuarticEase.prototype.easeInCore = function (gradient) {
  48616. return (gradient * gradient * gradient * gradient);
  48617. };
  48618. return QuarticEase;
  48619. }(EasingFunction));
  48620. BABYLON.QuarticEase = QuarticEase;
  48621. var QuinticEase = /** @class */ (function (_super) {
  48622. __extends(QuinticEase, _super);
  48623. function QuinticEase() {
  48624. return _super !== null && _super.apply(this, arguments) || this;
  48625. }
  48626. QuinticEase.prototype.easeInCore = function (gradient) {
  48627. return (gradient * gradient * gradient * gradient * gradient);
  48628. };
  48629. return QuinticEase;
  48630. }(EasingFunction));
  48631. BABYLON.QuinticEase = QuinticEase;
  48632. var SineEase = /** @class */ (function (_super) {
  48633. __extends(SineEase, _super);
  48634. function SineEase() {
  48635. return _super !== null && _super.apply(this, arguments) || this;
  48636. }
  48637. SineEase.prototype.easeInCore = function (gradient) {
  48638. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48639. };
  48640. return SineEase;
  48641. }(EasingFunction));
  48642. BABYLON.SineEase = SineEase;
  48643. var BezierCurveEase = /** @class */ (function (_super) {
  48644. __extends(BezierCurveEase, _super);
  48645. function BezierCurveEase(x1, y1, x2, y2) {
  48646. if (x1 === void 0) { x1 = 0; }
  48647. if (y1 === void 0) { y1 = 0; }
  48648. if (x2 === void 0) { x2 = 1; }
  48649. if (y2 === void 0) { y2 = 1; }
  48650. var _this = _super.call(this) || this;
  48651. _this.x1 = x1;
  48652. _this.y1 = y1;
  48653. _this.x2 = x2;
  48654. _this.y2 = y2;
  48655. return _this;
  48656. }
  48657. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48658. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48659. };
  48660. return BezierCurveEase;
  48661. }(EasingFunction));
  48662. BABYLON.BezierCurveEase = BezierCurveEase;
  48663. })(BABYLON || (BABYLON = {}));
  48664. //# sourceMappingURL=babylon.easing.js.map
  48665. "use strict";
  48666. var BABYLON;
  48667. (function (BABYLON) {
  48668. var Condition = /** @class */ (function () {
  48669. function Condition(actionManager) {
  48670. this._actionManager = actionManager;
  48671. }
  48672. Condition.prototype.isValid = function () {
  48673. return true;
  48674. };
  48675. Condition.prototype._getProperty = function (propertyPath) {
  48676. return this._actionManager._getProperty(propertyPath);
  48677. };
  48678. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48679. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48680. };
  48681. Condition.prototype.serialize = function () {
  48682. };
  48683. Condition.prototype._serialize = function (serializedCondition) {
  48684. return {
  48685. type: 2,
  48686. children: [],
  48687. name: serializedCondition.name,
  48688. properties: serializedCondition.properties
  48689. };
  48690. };
  48691. return Condition;
  48692. }());
  48693. BABYLON.Condition = Condition;
  48694. var ValueCondition = /** @class */ (function (_super) {
  48695. __extends(ValueCondition, _super);
  48696. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48697. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48698. var _this = _super.call(this, actionManager) || this;
  48699. _this.propertyPath = propertyPath;
  48700. _this.value = value;
  48701. _this.operator = operator;
  48702. _this._target = target;
  48703. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48704. _this._property = _this._getProperty(_this.propertyPath);
  48705. return _this;
  48706. }
  48707. Object.defineProperty(ValueCondition, "IsEqual", {
  48708. get: function () {
  48709. return ValueCondition._IsEqual;
  48710. },
  48711. enumerable: true,
  48712. configurable: true
  48713. });
  48714. Object.defineProperty(ValueCondition, "IsDifferent", {
  48715. get: function () {
  48716. return ValueCondition._IsDifferent;
  48717. },
  48718. enumerable: true,
  48719. configurable: true
  48720. });
  48721. Object.defineProperty(ValueCondition, "IsGreater", {
  48722. get: function () {
  48723. return ValueCondition._IsGreater;
  48724. },
  48725. enumerable: true,
  48726. configurable: true
  48727. });
  48728. Object.defineProperty(ValueCondition, "IsLesser", {
  48729. get: function () {
  48730. return ValueCondition._IsLesser;
  48731. },
  48732. enumerable: true,
  48733. configurable: true
  48734. });
  48735. // Methods
  48736. ValueCondition.prototype.isValid = function () {
  48737. switch (this.operator) {
  48738. case ValueCondition.IsGreater:
  48739. return this._effectiveTarget[this._property] > this.value;
  48740. case ValueCondition.IsLesser:
  48741. return this._effectiveTarget[this._property] < this.value;
  48742. case ValueCondition.IsEqual:
  48743. case ValueCondition.IsDifferent:
  48744. var check;
  48745. if (this.value.equals) {
  48746. check = this.value.equals(this._effectiveTarget[this._property]);
  48747. }
  48748. else {
  48749. check = this.value === this._effectiveTarget[this._property];
  48750. }
  48751. return this.operator === ValueCondition.IsEqual ? check : !check;
  48752. }
  48753. return false;
  48754. };
  48755. ValueCondition.prototype.serialize = function () {
  48756. return this._serialize({
  48757. name: "ValueCondition",
  48758. properties: [
  48759. BABYLON.Action._GetTargetProperty(this._target),
  48760. { name: "propertyPath", value: this.propertyPath },
  48761. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48762. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48763. ]
  48764. });
  48765. };
  48766. ValueCondition.GetOperatorName = function (operator) {
  48767. switch (operator) {
  48768. case ValueCondition._IsEqual: return "IsEqual";
  48769. case ValueCondition._IsDifferent: return "IsDifferent";
  48770. case ValueCondition._IsGreater: return "IsGreater";
  48771. case ValueCondition._IsLesser: return "IsLesser";
  48772. default: return "";
  48773. }
  48774. };
  48775. // Statics
  48776. ValueCondition._IsEqual = 0;
  48777. ValueCondition._IsDifferent = 1;
  48778. ValueCondition._IsGreater = 2;
  48779. ValueCondition._IsLesser = 3;
  48780. return ValueCondition;
  48781. }(Condition));
  48782. BABYLON.ValueCondition = ValueCondition;
  48783. var PredicateCondition = /** @class */ (function (_super) {
  48784. __extends(PredicateCondition, _super);
  48785. function PredicateCondition(actionManager, predicate) {
  48786. var _this = _super.call(this, actionManager) || this;
  48787. _this.predicate = predicate;
  48788. return _this;
  48789. }
  48790. PredicateCondition.prototype.isValid = function () {
  48791. return this.predicate();
  48792. };
  48793. return PredicateCondition;
  48794. }(Condition));
  48795. BABYLON.PredicateCondition = PredicateCondition;
  48796. var StateCondition = /** @class */ (function (_super) {
  48797. __extends(StateCondition, _super);
  48798. function StateCondition(actionManager, target, value) {
  48799. var _this = _super.call(this, actionManager) || this;
  48800. _this.value = value;
  48801. _this._target = target;
  48802. return _this;
  48803. }
  48804. // Methods
  48805. StateCondition.prototype.isValid = function () {
  48806. return this._target.state === this.value;
  48807. };
  48808. StateCondition.prototype.serialize = function () {
  48809. return this._serialize({
  48810. name: "StateCondition",
  48811. properties: [
  48812. BABYLON.Action._GetTargetProperty(this._target),
  48813. { name: "value", value: this.value }
  48814. ]
  48815. });
  48816. };
  48817. return StateCondition;
  48818. }(Condition));
  48819. BABYLON.StateCondition = StateCondition;
  48820. })(BABYLON || (BABYLON = {}));
  48821. //# sourceMappingURL=babylon.condition.js.map
  48822. "use strict";
  48823. var BABYLON;
  48824. (function (BABYLON) {
  48825. var Action = /** @class */ (function () {
  48826. function Action(triggerOptions, condition) {
  48827. this.triggerOptions = triggerOptions;
  48828. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48829. if (triggerOptions.parameter) {
  48830. this.trigger = triggerOptions.trigger;
  48831. this._triggerParameter = triggerOptions.parameter;
  48832. }
  48833. else {
  48834. this.trigger = triggerOptions;
  48835. }
  48836. this._nextActiveAction = this;
  48837. this._condition = condition;
  48838. }
  48839. // Methods
  48840. Action.prototype._prepare = function () {
  48841. };
  48842. Action.prototype.getTriggerParameter = function () {
  48843. return this._triggerParameter;
  48844. };
  48845. Action.prototype._executeCurrent = function (evt) {
  48846. if (this._nextActiveAction._condition) {
  48847. var condition = this._nextActiveAction._condition;
  48848. var currentRenderId = this._actionManager.getScene().getRenderId();
  48849. // We cache the current evaluation for the current frame
  48850. if (condition._evaluationId === currentRenderId) {
  48851. if (!condition._currentResult) {
  48852. return;
  48853. }
  48854. }
  48855. else {
  48856. condition._evaluationId = currentRenderId;
  48857. if (!condition.isValid()) {
  48858. condition._currentResult = false;
  48859. return;
  48860. }
  48861. condition._currentResult = true;
  48862. }
  48863. }
  48864. this.onBeforeExecuteObservable.notifyObservers(this);
  48865. this._nextActiveAction.execute(evt);
  48866. this.skipToNextActiveAction();
  48867. };
  48868. Action.prototype.execute = function (evt) {
  48869. };
  48870. Action.prototype.skipToNextActiveAction = function () {
  48871. if (this._nextActiveAction._child) {
  48872. if (!this._nextActiveAction._child._actionManager) {
  48873. this._nextActiveAction._child._actionManager = this._actionManager;
  48874. }
  48875. this._nextActiveAction = this._nextActiveAction._child;
  48876. }
  48877. else {
  48878. this._nextActiveAction = this;
  48879. }
  48880. };
  48881. Action.prototype.then = function (action) {
  48882. this._child = action;
  48883. action._actionManager = this._actionManager;
  48884. action._prepare();
  48885. return action;
  48886. };
  48887. Action.prototype._getProperty = function (propertyPath) {
  48888. return this._actionManager._getProperty(propertyPath);
  48889. };
  48890. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48891. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48892. };
  48893. Action.prototype.serialize = function (parent) {
  48894. };
  48895. // Called by BABYLON.Action objects in serialize(...). Internal use
  48896. Action.prototype._serialize = function (serializedAction, parent) {
  48897. var serializationObject = {
  48898. type: 1,
  48899. children: [],
  48900. name: serializedAction.name,
  48901. properties: serializedAction.properties || []
  48902. };
  48903. // Serialize child
  48904. if (this._child) {
  48905. this._child.serialize(serializationObject);
  48906. }
  48907. // Check if "this" has a condition
  48908. if (this._condition) {
  48909. var serializedCondition = this._condition.serialize();
  48910. serializedCondition.children.push(serializationObject);
  48911. if (parent) {
  48912. parent.children.push(serializedCondition);
  48913. }
  48914. return serializedCondition;
  48915. }
  48916. if (parent) {
  48917. parent.children.push(serializationObject);
  48918. }
  48919. return serializationObject;
  48920. };
  48921. Action._SerializeValueAsString = function (value) {
  48922. if (typeof value === "number") {
  48923. return value.toString();
  48924. }
  48925. if (typeof value === "boolean") {
  48926. return value ? "true" : "false";
  48927. }
  48928. if (value instanceof BABYLON.Vector2) {
  48929. return value.x + ", " + value.y;
  48930. }
  48931. if (value instanceof BABYLON.Vector3) {
  48932. return value.x + ", " + value.y + ", " + value.z;
  48933. }
  48934. if (value instanceof BABYLON.Color3) {
  48935. return value.r + ", " + value.g + ", " + value.b;
  48936. }
  48937. if (value instanceof BABYLON.Color4) {
  48938. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48939. }
  48940. return value; // string
  48941. };
  48942. Action._GetTargetProperty = function (target) {
  48943. return {
  48944. name: "target",
  48945. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48946. : target instanceof BABYLON.Light ? "LightProperties"
  48947. : target instanceof BABYLON.Camera ? "CameraProperties"
  48948. : "SceneProperties",
  48949. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48950. };
  48951. };
  48952. return Action;
  48953. }());
  48954. BABYLON.Action = Action;
  48955. })(BABYLON || (BABYLON = {}));
  48956. //# sourceMappingURL=babylon.action.js.map
  48957. "use strict";
  48958. var BABYLON;
  48959. (function (BABYLON) {
  48960. /**
  48961. * ActionEvent is the event beint sent when an action is triggered.
  48962. */
  48963. var ActionEvent = /** @class */ (function () {
  48964. /**
  48965. * @param source The mesh or sprite that triggered the action.
  48966. * @param pointerX The X mouse cursor position at the time of the event
  48967. * @param pointerY The Y mouse cursor position at the time of the event
  48968. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48969. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48970. */
  48971. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48972. this.source = source;
  48973. this.pointerX = pointerX;
  48974. this.pointerY = pointerY;
  48975. this.meshUnderPointer = meshUnderPointer;
  48976. this.sourceEvent = sourceEvent;
  48977. this.additionalData = additionalData;
  48978. }
  48979. /**
  48980. * Helper function to auto-create an ActionEvent from a source mesh.
  48981. * @param source The source mesh that triggered the event
  48982. * @param evt {Event} The original (browser) event
  48983. */
  48984. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48985. var scene = source.getScene();
  48986. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48987. };
  48988. /**
  48989. * Helper function to auto-create an ActionEvent from a source mesh.
  48990. * @param source The source sprite that triggered the event
  48991. * @param scene Scene associated with the sprite
  48992. * @param evt {Event} The original (browser) event
  48993. */
  48994. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48995. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48996. };
  48997. /**
  48998. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48999. * @param scene the scene where the event occurred
  49000. * @param evt {Event} The original (browser) event
  49001. */
  49002. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49003. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49004. };
  49005. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49006. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49007. };
  49008. return ActionEvent;
  49009. }());
  49010. BABYLON.ActionEvent = ActionEvent;
  49011. /**
  49012. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49013. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49014. */
  49015. var ActionManager = /** @class */ (function () {
  49016. function ActionManager(scene) {
  49017. // Members
  49018. this.actions = new Array();
  49019. this.hoverCursor = '';
  49020. this._scene = scene;
  49021. scene._actionManagers.push(this);
  49022. }
  49023. Object.defineProperty(ActionManager, "NothingTrigger", {
  49024. get: function () {
  49025. return ActionManager._NothingTrigger;
  49026. },
  49027. enumerable: true,
  49028. configurable: true
  49029. });
  49030. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49031. get: function () {
  49032. return ActionManager._OnPickTrigger;
  49033. },
  49034. enumerable: true,
  49035. configurable: true
  49036. });
  49037. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49038. get: function () {
  49039. return ActionManager._OnLeftPickTrigger;
  49040. },
  49041. enumerable: true,
  49042. configurable: true
  49043. });
  49044. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49045. get: function () {
  49046. return ActionManager._OnRightPickTrigger;
  49047. },
  49048. enumerable: true,
  49049. configurable: true
  49050. });
  49051. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49052. get: function () {
  49053. return ActionManager._OnCenterPickTrigger;
  49054. },
  49055. enumerable: true,
  49056. configurable: true
  49057. });
  49058. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49059. get: function () {
  49060. return ActionManager._OnPickDownTrigger;
  49061. },
  49062. enumerable: true,
  49063. configurable: true
  49064. });
  49065. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49066. get: function () {
  49067. return ActionManager._OnDoublePickTrigger;
  49068. },
  49069. enumerable: true,
  49070. configurable: true
  49071. });
  49072. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49073. get: function () {
  49074. return ActionManager._OnPickUpTrigger;
  49075. },
  49076. enumerable: true,
  49077. configurable: true
  49078. });
  49079. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49080. /// This trigger will only be raised if you also declared a OnPickDown
  49081. get: function () {
  49082. return ActionManager._OnPickOutTrigger;
  49083. },
  49084. enumerable: true,
  49085. configurable: true
  49086. });
  49087. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49088. get: function () {
  49089. return ActionManager._OnLongPressTrigger;
  49090. },
  49091. enumerable: true,
  49092. configurable: true
  49093. });
  49094. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49095. get: function () {
  49096. return ActionManager._OnPointerOverTrigger;
  49097. },
  49098. enumerable: true,
  49099. configurable: true
  49100. });
  49101. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49102. get: function () {
  49103. return ActionManager._OnPointerOutTrigger;
  49104. },
  49105. enumerable: true,
  49106. configurable: true
  49107. });
  49108. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49109. get: function () {
  49110. return ActionManager._OnEveryFrameTrigger;
  49111. },
  49112. enumerable: true,
  49113. configurable: true
  49114. });
  49115. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49116. get: function () {
  49117. return ActionManager._OnIntersectionEnterTrigger;
  49118. },
  49119. enumerable: true,
  49120. configurable: true
  49121. });
  49122. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49123. get: function () {
  49124. return ActionManager._OnIntersectionExitTrigger;
  49125. },
  49126. enumerable: true,
  49127. configurable: true
  49128. });
  49129. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49130. get: function () {
  49131. return ActionManager._OnKeyDownTrigger;
  49132. },
  49133. enumerable: true,
  49134. configurable: true
  49135. });
  49136. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49137. get: function () {
  49138. return ActionManager._OnKeyUpTrigger;
  49139. },
  49140. enumerable: true,
  49141. configurable: true
  49142. });
  49143. // Methods
  49144. ActionManager.prototype.dispose = function () {
  49145. var index = this._scene._actionManagers.indexOf(this);
  49146. for (var i = 0; i < this.actions.length; i++) {
  49147. var action = this.actions[i];
  49148. ActionManager.Triggers[action.trigger]--;
  49149. if (ActionManager.Triggers[action.trigger] === 0) {
  49150. delete ActionManager.Triggers[action.trigger];
  49151. }
  49152. }
  49153. if (index > -1) {
  49154. this._scene._actionManagers.splice(index, 1);
  49155. }
  49156. };
  49157. ActionManager.prototype.getScene = function () {
  49158. return this._scene;
  49159. };
  49160. /**
  49161. * Does this action manager handles actions of any of the given triggers
  49162. * @param {number[]} triggers - the triggers to be tested
  49163. * @return {boolean} whether one (or more) of the triggers is handeled
  49164. */
  49165. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49166. for (var index = 0; index < this.actions.length; index++) {
  49167. var action = this.actions[index];
  49168. if (triggers.indexOf(action.trigger) > -1) {
  49169. return true;
  49170. }
  49171. }
  49172. return false;
  49173. };
  49174. /**
  49175. * Does this action manager handles actions of a given trigger
  49176. * @param {number} trigger - the trigger to be tested
  49177. * @return {boolean} whether the trigger is handeled
  49178. */
  49179. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49180. for (var index = 0; index < this.actions.length; index++) {
  49181. var action = this.actions[index];
  49182. if (action.trigger === trigger) {
  49183. return true;
  49184. }
  49185. }
  49186. return false;
  49187. };
  49188. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49189. /**
  49190. * Does this action manager has pointer triggers
  49191. * @return {boolean} whether or not it has pointer triggers
  49192. */
  49193. get: function () {
  49194. for (var index = 0; index < this.actions.length; index++) {
  49195. var action = this.actions[index];
  49196. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49197. return true;
  49198. }
  49199. }
  49200. return false;
  49201. },
  49202. enumerable: true,
  49203. configurable: true
  49204. });
  49205. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49206. /**
  49207. * Does this action manager has pick triggers
  49208. * @return {boolean} whether or not it has pick triggers
  49209. */
  49210. get: function () {
  49211. for (var index = 0; index < this.actions.length; index++) {
  49212. var action = this.actions[index];
  49213. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49214. return true;
  49215. }
  49216. }
  49217. return false;
  49218. },
  49219. enumerable: true,
  49220. configurable: true
  49221. });
  49222. Object.defineProperty(ActionManager, "HasTriggers", {
  49223. /**
  49224. * Does exist one action manager with at least one trigger
  49225. * @return {boolean} whether or not it exists one action manager with one trigger
  49226. **/
  49227. get: function () {
  49228. for (var t in ActionManager.Triggers) {
  49229. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49230. return true;
  49231. }
  49232. }
  49233. return false;
  49234. },
  49235. enumerable: true,
  49236. configurable: true
  49237. });
  49238. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49239. /**
  49240. * Does exist one action manager with at least one pick trigger
  49241. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49242. **/
  49243. get: function () {
  49244. for (var t in ActionManager.Triggers) {
  49245. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49246. var t_int = parseInt(t);
  49247. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49248. return true;
  49249. }
  49250. }
  49251. }
  49252. return false;
  49253. },
  49254. enumerable: true,
  49255. configurable: true
  49256. });
  49257. /**
  49258. * Does exist one action manager that handles actions of a given trigger
  49259. * @param {number} trigger - the trigger to be tested
  49260. * @return {boolean} whether the trigger is handeled by at least one action manager
  49261. **/
  49262. ActionManager.HasSpecificTrigger = function (trigger) {
  49263. for (var t in ActionManager.Triggers) {
  49264. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49265. var t_int = parseInt(t);
  49266. if (t_int === trigger) {
  49267. return true;
  49268. }
  49269. }
  49270. }
  49271. return false;
  49272. };
  49273. /**
  49274. * Registers an action to this action manager
  49275. * @param {BABYLON.Action} action - the action to be registered
  49276. * @return {BABYLON.Action} the action amended (prepared) after registration
  49277. */
  49278. ActionManager.prototype.registerAction = function (action) {
  49279. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49280. if (this.getScene().actionManager !== this) {
  49281. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49282. return null;
  49283. }
  49284. }
  49285. this.actions.push(action);
  49286. if (ActionManager.Triggers[action.trigger]) {
  49287. ActionManager.Triggers[action.trigger]++;
  49288. }
  49289. else {
  49290. ActionManager.Triggers[action.trigger] = 1;
  49291. }
  49292. action._actionManager = this;
  49293. action._prepare();
  49294. return action;
  49295. };
  49296. /**
  49297. * Unregisters an action to this action manager
  49298. * @param action The action to be unregistered
  49299. * @return whether the action has been unregistered
  49300. */
  49301. ActionManager.prototype.unregisterAction = function (action) {
  49302. var index = this.actions.indexOf(action);
  49303. if (index !== -1) {
  49304. this.actions.splice(index, 1);
  49305. ActionManager.Triggers[action.trigger] -= 1;
  49306. if (ActionManager.Triggers[action.trigger] === 0) {
  49307. delete ActionManager.Triggers[action.trigger];
  49308. }
  49309. delete action._actionManager;
  49310. return true;
  49311. }
  49312. return false;
  49313. };
  49314. /**
  49315. * Process a specific trigger
  49316. * @param {number} trigger - the trigger to process
  49317. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49318. */
  49319. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49320. for (var index = 0; index < this.actions.length; index++) {
  49321. var action = this.actions[index];
  49322. if (action.trigger === trigger) {
  49323. if (evt) {
  49324. if (trigger === ActionManager.OnKeyUpTrigger
  49325. || trigger === ActionManager.OnKeyDownTrigger) {
  49326. var parameter = action.getTriggerParameter();
  49327. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49328. if (!parameter.toLowerCase) {
  49329. continue;
  49330. }
  49331. var lowerCase = parameter.toLowerCase();
  49332. if (lowerCase !== evt.sourceEvent.key) {
  49333. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49334. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49335. if (actualkey !== lowerCase) {
  49336. continue;
  49337. }
  49338. }
  49339. }
  49340. }
  49341. }
  49342. action._executeCurrent(evt);
  49343. }
  49344. }
  49345. };
  49346. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49347. var properties = propertyPath.split(".");
  49348. for (var index = 0; index < properties.length - 1; index++) {
  49349. target = target[properties[index]];
  49350. }
  49351. return target;
  49352. };
  49353. ActionManager.prototype._getProperty = function (propertyPath) {
  49354. var properties = propertyPath.split(".");
  49355. return properties[properties.length - 1];
  49356. };
  49357. ActionManager.prototype.serialize = function (name) {
  49358. var root = {
  49359. children: new Array(),
  49360. name: name,
  49361. type: 3,
  49362. properties: new Array() // Empty for root but required
  49363. };
  49364. for (var i = 0; i < this.actions.length; i++) {
  49365. var triggerObject = {
  49366. type: 0,
  49367. children: new Array(),
  49368. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49369. properties: new Array()
  49370. };
  49371. var triggerOptions = this.actions[i].triggerOptions;
  49372. if (triggerOptions && typeof triggerOptions !== "number") {
  49373. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49374. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49375. }
  49376. else {
  49377. var parameter = {};
  49378. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49379. if (triggerOptions.parameter.mesh) {
  49380. parameter._meshId = triggerOptions.parameter.mesh.id;
  49381. }
  49382. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49383. }
  49384. }
  49385. // Serialize child action, recursively
  49386. this.actions[i].serialize(triggerObject);
  49387. // Add serialized trigger
  49388. root.children.push(triggerObject);
  49389. }
  49390. return root;
  49391. };
  49392. ActionManager.Parse = function (parsedActions, object, scene) {
  49393. var actionManager = new ActionManager(scene);
  49394. if (object === null)
  49395. scene.actionManager = actionManager;
  49396. else
  49397. object.actionManager = actionManager;
  49398. // instanciate a new object
  49399. var instanciate = function (name, params) {
  49400. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49401. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49402. newInstance.constructor.apply(newInstance, params);
  49403. return newInstance;
  49404. };
  49405. var parseParameter = function (name, value, target, propertyPath) {
  49406. if (propertyPath === null) {
  49407. // String, boolean or float
  49408. var floatValue = parseFloat(value);
  49409. if (value === "true" || value === "false")
  49410. return value === "true";
  49411. else
  49412. return isNaN(floatValue) ? value : floatValue;
  49413. }
  49414. var effectiveTarget = propertyPath.split(".");
  49415. var values = value.split(",");
  49416. // Get effective Target
  49417. for (var i = 0; i < effectiveTarget.length; i++) {
  49418. target = target[effectiveTarget[i]];
  49419. }
  49420. // Return appropriate value with its type
  49421. if (typeof (target) === "boolean")
  49422. return values[0] === "true";
  49423. if (typeof (target) === "string")
  49424. return values[0];
  49425. // Parameters with multiple values such as Vector3 etc.
  49426. var split = new Array();
  49427. for (var i = 0; i < values.length; i++)
  49428. split.push(parseFloat(values[i]));
  49429. if (target instanceof BABYLON.Vector3)
  49430. return BABYLON.Vector3.FromArray(split);
  49431. if (target instanceof BABYLON.Vector4)
  49432. return BABYLON.Vector4.FromArray(split);
  49433. if (target instanceof BABYLON.Color3)
  49434. return BABYLON.Color3.FromArray(split);
  49435. if (target instanceof BABYLON.Color4)
  49436. return BABYLON.Color4.FromArray(split);
  49437. return parseFloat(values[0]);
  49438. };
  49439. // traverse graph per trigger
  49440. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49441. if (combineArray === void 0) { combineArray = null; }
  49442. if (parsedAction.detached)
  49443. return;
  49444. var parameters = new Array();
  49445. var target = null;
  49446. var propertyPath = null;
  49447. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49448. // Parameters
  49449. if (parsedAction.type === 2)
  49450. parameters.push(actionManager);
  49451. else
  49452. parameters.push(trigger);
  49453. if (combine) {
  49454. var actions = new Array();
  49455. for (var j = 0; j < parsedAction.combine.length; j++) {
  49456. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49457. }
  49458. parameters.push(actions);
  49459. }
  49460. else {
  49461. for (var i = 0; i < parsedAction.properties.length; i++) {
  49462. var value = parsedAction.properties[i].value;
  49463. var name = parsedAction.properties[i].name;
  49464. var targetType = parsedAction.properties[i].targetType;
  49465. if (name === "target")
  49466. if (targetType !== null && targetType === "SceneProperties")
  49467. value = target = scene;
  49468. else
  49469. value = target = scene.getNodeByName(value);
  49470. else if (name === "parent")
  49471. value = scene.getNodeByName(value);
  49472. else if (name === "sound")
  49473. value = scene.getSoundByName(value);
  49474. else if (name !== "propertyPath") {
  49475. if (parsedAction.type === 2 && name === "operator")
  49476. value = BABYLON.ValueCondition[value];
  49477. else
  49478. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49479. }
  49480. else {
  49481. propertyPath = value;
  49482. }
  49483. parameters.push(value);
  49484. }
  49485. }
  49486. if (combineArray === null) {
  49487. parameters.push(condition);
  49488. }
  49489. else {
  49490. parameters.push(null);
  49491. }
  49492. // If interpolate value action
  49493. if (parsedAction.name === "InterpolateValueAction") {
  49494. var param = parameters[parameters.length - 2];
  49495. parameters[parameters.length - 1] = param;
  49496. parameters[parameters.length - 2] = condition;
  49497. }
  49498. // Action or condition(s) and not CombineAction
  49499. var newAction = instanciate(parsedAction.name, parameters);
  49500. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49501. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49502. if (action)
  49503. action.then(nothing);
  49504. else
  49505. actionManager.registerAction(nothing);
  49506. action = nothing;
  49507. }
  49508. if (combineArray === null) {
  49509. if (newAction instanceof BABYLON.Condition) {
  49510. condition = newAction;
  49511. newAction = action;
  49512. }
  49513. else {
  49514. condition = null;
  49515. if (action)
  49516. action.then(newAction);
  49517. else
  49518. actionManager.registerAction(newAction);
  49519. }
  49520. }
  49521. else {
  49522. combineArray.push(newAction);
  49523. }
  49524. for (var i = 0; i < parsedAction.children.length; i++)
  49525. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49526. };
  49527. // triggers
  49528. for (var i = 0; i < parsedActions.children.length; i++) {
  49529. var triggerParams;
  49530. var trigger = parsedActions.children[i];
  49531. if (trigger.properties.length > 0) {
  49532. var param = trigger.properties[0].value;
  49533. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49534. if (value._meshId) {
  49535. value.mesh = scene.getMeshByID(value._meshId);
  49536. }
  49537. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49538. }
  49539. else
  49540. triggerParams = ActionManager[trigger.name];
  49541. for (var j = 0; j < trigger.children.length; j++) {
  49542. if (!trigger.detached)
  49543. traverse(trigger.children[j], triggerParams, null, null);
  49544. }
  49545. }
  49546. };
  49547. ActionManager.GetTriggerName = function (trigger) {
  49548. switch (trigger) {
  49549. case 0: return "NothingTrigger";
  49550. case 1: return "OnPickTrigger";
  49551. case 2: return "OnLeftPickTrigger";
  49552. case 3: return "OnRightPickTrigger";
  49553. case 4: return "OnCenterPickTrigger";
  49554. case 5: return "OnPickDownTrigger";
  49555. case 6: return "OnPickUpTrigger";
  49556. case 7: return "OnLongPressTrigger";
  49557. case 8: return "OnPointerOverTrigger";
  49558. case 9: return "OnPointerOutTrigger";
  49559. case 10: return "OnEveryFrameTrigger";
  49560. case 11: return "OnIntersectionEnterTrigger";
  49561. case 12: return "OnIntersectionExitTrigger";
  49562. case 13: return "OnKeyDownTrigger";
  49563. case 14: return "OnKeyUpTrigger";
  49564. case 15: return "OnPickOutTrigger";
  49565. default: return "";
  49566. }
  49567. };
  49568. // Statics
  49569. ActionManager._NothingTrigger = 0;
  49570. ActionManager._OnPickTrigger = 1;
  49571. ActionManager._OnLeftPickTrigger = 2;
  49572. ActionManager._OnRightPickTrigger = 3;
  49573. ActionManager._OnCenterPickTrigger = 4;
  49574. ActionManager._OnPickDownTrigger = 5;
  49575. ActionManager._OnDoublePickTrigger = 6;
  49576. ActionManager._OnPickUpTrigger = 7;
  49577. ActionManager._OnLongPressTrigger = 8;
  49578. ActionManager._OnPointerOverTrigger = 9;
  49579. ActionManager._OnPointerOutTrigger = 10;
  49580. ActionManager._OnEveryFrameTrigger = 11;
  49581. ActionManager._OnIntersectionEnterTrigger = 12;
  49582. ActionManager._OnIntersectionExitTrigger = 13;
  49583. ActionManager._OnKeyDownTrigger = 14;
  49584. ActionManager._OnKeyUpTrigger = 15;
  49585. ActionManager._OnPickOutTrigger = 16;
  49586. ActionManager.Triggers = {};
  49587. return ActionManager;
  49588. }());
  49589. BABYLON.ActionManager = ActionManager;
  49590. })(BABYLON || (BABYLON = {}));
  49591. //# sourceMappingURL=babylon.actionManager.js.map
  49592. "use strict";
  49593. var BABYLON;
  49594. (function (BABYLON) {
  49595. var InterpolateValueAction = /** @class */ (function (_super) {
  49596. __extends(InterpolateValueAction, _super);
  49597. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49598. if (duration === void 0) { duration = 1000; }
  49599. var _this = _super.call(this, triggerOptions, condition) || this;
  49600. _this.propertyPath = propertyPath;
  49601. _this.value = value;
  49602. _this.duration = duration;
  49603. _this.stopOtherAnimations = stopOtherAnimations;
  49604. _this.onInterpolationDone = onInterpolationDone;
  49605. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49606. _this._target = _this._effectiveTarget = target;
  49607. return _this;
  49608. }
  49609. InterpolateValueAction.prototype._prepare = function () {
  49610. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49611. this._property = this._getProperty(this.propertyPath);
  49612. };
  49613. InterpolateValueAction.prototype.execute = function () {
  49614. var _this = this;
  49615. var scene = this._actionManager.getScene();
  49616. var keys = [
  49617. {
  49618. frame: 0,
  49619. value: this._effectiveTarget[this._property]
  49620. }, {
  49621. frame: 100,
  49622. value: this.value
  49623. }
  49624. ];
  49625. var dataType;
  49626. if (typeof this.value === "number") {
  49627. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49628. }
  49629. else if (this.value instanceof BABYLON.Color3) {
  49630. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49631. }
  49632. else if (this.value instanceof BABYLON.Vector3) {
  49633. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49634. }
  49635. else if (this.value instanceof BABYLON.Matrix) {
  49636. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49637. }
  49638. else if (this.value instanceof BABYLON.Quaternion) {
  49639. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49640. }
  49641. else {
  49642. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49643. return;
  49644. }
  49645. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49646. animation.setKeys(keys);
  49647. if (this.stopOtherAnimations) {
  49648. scene.stopAnimation(this._effectiveTarget);
  49649. }
  49650. var wrapper = function () {
  49651. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49652. if (_this.onInterpolationDone) {
  49653. _this.onInterpolationDone();
  49654. }
  49655. };
  49656. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49657. };
  49658. InterpolateValueAction.prototype.serialize = function (parent) {
  49659. return _super.prototype._serialize.call(this, {
  49660. name: "InterpolateValueAction",
  49661. properties: [
  49662. BABYLON.Action._GetTargetProperty(this._target),
  49663. { name: "propertyPath", value: this.propertyPath },
  49664. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49665. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49666. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49667. ]
  49668. }, parent);
  49669. };
  49670. return InterpolateValueAction;
  49671. }(BABYLON.Action));
  49672. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49673. })(BABYLON || (BABYLON = {}));
  49674. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49675. "use strict";
  49676. var BABYLON;
  49677. (function (BABYLON) {
  49678. var SwitchBooleanAction = /** @class */ (function (_super) {
  49679. __extends(SwitchBooleanAction, _super);
  49680. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49681. var _this = _super.call(this, triggerOptions, condition) || this;
  49682. _this.propertyPath = propertyPath;
  49683. _this._target = _this._effectiveTarget = target;
  49684. return _this;
  49685. }
  49686. SwitchBooleanAction.prototype._prepare = function () {
  49687. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49688. this._property = this._getProperty(this.propertyPath);
  49689. };
  49690. SwitchBooleanAction.prototype.execute = function () {
  49691. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49692. };
  49693. SwitchBooleanAction.prototype.serialize = function (parent) {
  49694. return _super.prototype._serialize.call(this, {
  49695. name: "SwitchBooleanAction",
  49696. properties: [
  49697. BABYLON.Action._GetTargetProperty(this._target),
  49698. { name: "propertyPath", value: this.propertyPath }
  49699. ]
  49700. }, parent);
  49701. };
  49702. return SwitchBooleanAction;
  49703. }(BABYLON.Action));
  49704. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49705. var SetStateAction = /** @class */ (function (_super) {
  49706. __extends(SetStateAction, _super);
  49707. function SetStateAction(triggerOptions, target, value, condition) {
  49708. var _this = _super.call(this, triggerOptions, condition) || this;
  49709. _this.value = value;
  49710. _this._target = target;
  49711. return _this;
  49712. }
  49713. SetStateAction.prototype.execute = function () {
  49714. this._target.state = this.value;
  49715. };
  49716. SetStateAction.prototype.serialize = function (parent) {
  49717. return _super.prototype._serialize.call(this, {
  49718. name: "SetStateAction",
  49719. properties: [
  49720. BABYLON.Action._GetTargetProperty(this._target),
  49721. { name: "value", value: this.value }
  49722. ]
  49723. }, parent);
  49724. };
  49725. return SetStateAction;
  49726. }(BABYLON.Action));
  49727. BABYLON.SetStateAction = SetStateAction;
  49728. var SetValueAction = /** @class */ (function (_super) {
  49729. __extends(SetValueAction, _super);
  49730. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49731. var _this = _super.call(this, triggerOptions, condition) || this;
  49732. _this.propertyPath = propertyPath;
  49733. _this.value = value;
  49734. _this._target = _this._effectiveTarget = target;
  49735. return _this;
  49736. }
  49737. SetValueAction.prototype._prepare = function () {
  49738. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49739. this._property = this._getProperty(this.propertyPath);
  49740. };
  49741. SetValueAction.prototype.execute = function () {
  49742. this._effectiveTarget[this._property] = this.value;
  49743. if (this._target.markAsDirty) {
  49744. this._target.markAsDirty(this._property);
  49745. }
  49746. };
  49747. SetValueAction.prototype.serialize = function (parent) {
  49748. return _super.prototype._serialize.call(this, {
  49749. name: "SetValueAction",
  49750. properties: [
  49751. BABYLON.Action._GetTargetProperty(this._target),
  49752. { name: "propertyPath", value: this.propertyPath },
  49753. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49754. ]
  49755. }, parent);
  49756. };
  49757. return SetValueAction;
  49758. }(BABYLON.Action));
  49759. BABYLON.SetValueAction = SetValueAction;
  49760. var IncrementValueAction = /** @class */ (function (_super) {
  49761. __extends(IncrementValueAction, _super);
  49762. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49763. var _this = _super.call(this, triggerOptions, condition) || this;
  49764. _this.propertyPath = propertyPath;
  49765. _this.value = value;
  49766. _this._target = _this._effectiveTarget = target;
  49767. return _this;
  49768. }
  49769. IncrementValueAction.prototype._prepare = function () {
  49770. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49771. this._property = this._getProperty(this.propertyPath);
  49772. if (typeof this._effectiveTarget[this._property] !== "number") {
  49773. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49774. }
  49775. };
  49776. IncrementValueAction.prototype.execute = function () {
  49777. this._effectiveTarget[this._property] += this.value;
  49778. if (this._target.markAsDirty) {
  49779. this._target.markAsDirty(this._property);
  49780. }
  49781. };
  49782. IncrementValueAction.prototype.serialize = function (parent) {
  49783. return _super.prototype._serialize.call(this, {
  49784. name: "IncrementValueAction",
  49785. properties: [
  49786. BABYLON.Action._GetTargetProperty(this._target),
  49787. { name: "propertyPath", value: this.propertyPath },
  49788. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49789. ]
  49790. }, parent);
  49791. };
  49792. return IncrementValueAction;
  49793. }(BABYLON.Action));
  49794. BABYLON.IncrementValueAction = IncrementValueAction;
  49795. var PlayAnimationAction = /** @class */ (function (_super) {
  49796. __extends(PlayAnimationAction, _super);
  49797. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49798. var _this = _super.call(this, triggerOptions, condition) || this;
  49799. _this.from = from;
  49800. _this.to = to;
  49801. _this.loop = loop;
  49802. _this._target = target;
  49803. return _this;
  49804. }
  49805. PlayAnimationAction.prototype._prepare = function () {
  49806. };
  49807. PlayAnimationAction.prototype.execute = function () {
  49808. var scene = this._actionManager.getScene();
  49809. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49810. };
  49811. PlayAnimationAction.prototype.serialize = function (parent) {
  49812. return _super.prototype._serialize.call(this, {
  49813. name: "PlayAnimationAction",
  49814. properties: [
  49815. BABYLON.Action._GetTargetProperty(this._target),
  49816. { name: "from", value: String(this.from) },
  49817. { name: "to", value: String(this.to) },
  49818. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49819. ]
  49820. }, parent);
  49821. };
  49822. return PlayAnimationAction;
  49823. }(BABYLON.Action));
  49824. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49825. var StopAnimationAction = /** @class */ (function (_super) {
  49826. __extends(StopAnimationAction, _super);
  49827. function StopAnimationAction(triggerOptions, target, condition) {
  49828. var _this = _super.call(this, triggerOptions, condition) || this;
  49829. _this._target = target;
  49830. return _this;
  49831. }
  49832. StopAnimationAction.prototype._prepare = function () {
  49833. };
  49834. StopAnimationAction.prototype.execute = function () {
  49835. var scene = this._actionManager.getScene();
  49836. scene.stopAnimation(this._target);
  49837. };
  49838. StopAnimationAction.prototype.serialize = function (parent) {
  49839. return _super.prototype._serialize.call(this, {
  49840. name: "StopAnimationAction",
  49841. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49842. }, parent);
  49843. };
  49844. return StopAnimationAction;
  49845. }(BABYLON.Action));
  49846. BABYLON.StopAnimationAction = StopAnimationAction;
  49847. var DoNothingAction = /** @class */ (function (_super) {
  49848. __extends(DoNothingAction, _super);
  49849. function DoNothingAction(triggerOptions, condition) {
  49850. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49851. return _super.call(this, triggerOptions, condition) || this;
  49852. }
  49853. DoNothingAction.prototype.execute = function () {
  49854. };
  49855. DoNothingAction.prototype.serialize = function (parent) {
  49856. return _super.prototype._serialize.call(this, {
  49857. name: "DoNothingAction",
  49858. properties: []
  49859. }, parent);
  49860. };
  49861. return DoNothingAction;
  49862. }(BABYLON.Action));
  49863. BABYLON.DoNothingAction = DoNothingAction;
  49864. var CombineAction = /** @class */ (function (_super) {
  49865. __extends(CombineAction, _super);
  49866. function CombineAction(triggerOptions, children, condition) {
  49867. var _this = _super.call(this, triggerOptions, condition) || this;
  49868. _this.children = children;
  49869. return _this;
  49870. }
  49871. CombineAction.prototype._prepare = function () {
  49872. for (var index = 0; index < this.children.length; index++) {
  49873. this.children[index]._actionManager = this._actionManager;
  49874. this.children[index]._prepare();
  49875. }
  49876. };
  49877. CombineAction.prototype.execute = function (evt) {
  49878. for (var index = 0; index < this.children.length; index++) {
  49879. this.children[index].execute(evt);
  49880. }
  49881. };
  49882. CombineAction.prototype.serialize = function (parent) {
  49883. var serializationObject = _super.prototype._serialize.call(this, {
  49884. name: "CombineAction",
  49885. properties: [],
  49886. combine: []
  49887. }, parent);
  49888. for (var i = 0; i < this.children.length; i++) {
  49889. serializationObject.combine.push(this.children[i].serialize(null));
  49890. }
  49891. return serializationObject;
  49892. };
  49893. return CombineAction;
  49894. }(BABYLON.Action));
  49895. BABYLON.CombineAction = CombineAction;
  49896. var ExecuteCodeAction = /** @class */ (function (_super) {
  49897. __extends(ExecuteCodeAction, _super);
  49898. function ExecuteCodeAction(triggerOptions, func, condition) {
  49899. var _this = _super.call(this, triggerOptions, condition) || this;
  49900. _this.func = func;
  49901. return _this;
  49902. }
  49903. ExecuteCodeAction.prototype.execute = function (evt) {
  49904. this.func(evt);
  49905. };
  49906. return ExecuteCodeAction;
  49907. }(BABYLON.Action));
  49908. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49909. var SetParentAction = /** @class */ (function (_super) {
  49910. __extends(SetParentAction, _super);
  49911. function SetParentAction(triggerOptions, target, parent, condition) {
  49912. var _this = _super.call(this, triggerOptions, condition) || this;
  49913. _this._target = target;
  49914. _this._parent = parent;
  49915. return _this;
  49916. }
  49917. SetParentAction.prototype._prepare = function () {
  49918. };
  49919. SetParentAction.prototype.execute = function () {
  49920. if (this._target.parent === this._parent) {
  49921. return;
  49922. }
  49923. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49924. invertParentWorldMatrix.invert();
  49925. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49926. this._target.parent = this._parent;
  49927. };
  49928. SetParentAction.prototype.serialize = function (parent) {
  49929. return _super.prototype._serialize.call(this, {
  49930. name: "SetParentAction",
  49931. properties: [
  49932. BABYLON.Action._GetTargetProperty(this._target),
  49933. BABYLON.Action._GetTargetProperty(this._parent),
  49934. ]
  49935. }, parent);
  49936. };
  49937. return SetParentAction;
  49938. }(BABYLON.Action));
  49939. BABYLON.SetParentAction = SetParentAction;
  49940. var PlaySoundAction = /** @class */ (function (_super) {
  49941. __extends(PlaySoundAction, _super);
  49942. function PlaySoundAction(triggerOptions, sound, condition) {
  49943. var _this = _super.call(this, triggerOptions, condition) || this;
  49944. _this._sound = sound;
  49945. return _this;
  49946. }
  49947. PlaySoundAction.prototype._prepare = function () {
  49948. };
  49949. PlaySoundAction.prototype.execute = function () {
  49950. if (this._sound !== undefined)
  49951. this._sound.play();
  49952. };
  49953. PlaySoundAction.prototype.serialize = function (parent) {
  49954. return _super.prototype._serialize.call(this, {
  49955. name: "PlaySoundAction",
  49956. properties: [{ name: "sound", value: this._sound.name }]
  49957. }, parent);
  49958. };
  49959. return PlaySoundAction;
  49960. }(BABYLON.Action));
  49961. BABYLON.PlaySoundAction = PlaySoundAction;
  49962. var StopSoundAction = /** @class */ (function (_super) {
  49963. __extends(StopSoundAction, _super);
  49964. function StopSoundAction(triggerOptions, sound, condition) {
  49965. var _this = _super.call(this, triggerOptions, condition) || this;
  49966. _this._sound = sound;
  49967. return _this;
  49968. }
  49969. StopSoundAction.prototype._prepare = function () {
  49970. };
  49971. StopSoundAction.prototype.execute = function () {
  49972. if (this._sound !== undefined)
  49973. this._sound.stop();
  49974. };
  49975. StopSoundAction.prototype.serialize = function (parent) {
  49976. return _super.prototype._serialize.call(this, {
  49977. name: "StopSoundAction",
  49978. properties: [{ name: "sound", value: this._sound.name }]
  49979. }, parent);
  49980. };
  49981. return StopSoundAction;
  49982. }(BABYLON.Action));
  49983. BABYLON.StopSoundAction = StopSoundAction;
  49984. })(BABYLON || (BABYLON = {}));
  49985. //# sourceMappingURL=babylon.directActions.js.map
  49986. "use strict";
  49987. var BABYLON;
  49988. (function (BABYLON) {
  49989. var SpriteManager = /** @class */ (function () {
  49990. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49991. if (epsilon === void 0) { epsilon = 0.01; }
  49992. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49993. this.name = name;
  49994. this.sprites = new Array();
  49995. this.renderingGroupId = 0;
  49996. this.layerMask = 0x0FFFFFFF;
  49997. this.fogEnabled = true;
  49998. this.isPickable = false;
  49999. /**
  50000. * An event triggered when the manager is disposed.
  50001. * @type {BABYLON.Observable}
  50002. */
  50003. this.onDisposeObservable = new BABYLON.Observable();
  50004. this._vertexBuffers = {};
  50005. this._capacity = capacity;
  50006. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50007. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50008. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50009. if (cellSize.width && cellSize.height) {
  50010. this.cellWidth = cellSize.width;
  50011. this.cellHeight = cellSize.height;
  50012. }
  50013. else if (cellSize !== undefined) {
  50014. this.cellWidth = cellSize;
  50015. this.cellHeight = cellSize;
  50016. }
  50017. else {
  50018. return;
  50019. }
  50020. this._epsilon = epsilon;
  50021. this._scene = scene;
  50022. this._scene.spriteManagers.push(this);
  50023. var indices = [];
  50024. var index = 0;
  50025. for (var count = 0; count < capacity; count++) {
  50026. indices.push(index);
  50027. indices.push(index + 1);
  50028. indices.push(index + 2);
  50029. indices.push(index);
  50030. indices.push(index + 2);
  50031. indices.push(index + 3);
  50032. index += 4;
  50033. }
  50034. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50035. // VBO
  50036. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50037. this._vertexData = new Float32Array(capacity * 16 * 4);
  50038. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50039. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50040. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50041. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50042. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50043. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50044. this._vertexBuffers["options"] = options;
  50045. this._vertexBuffers["cellInfo"] = cellInfo;
  50046. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50047. // Effects
  50048. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50049. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50050. }
  50051. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50052. set: function (callback) {
  50053. if (this._onDisposeObserver) {
  50054. this.onDisposeObservable.remove(this._onDisposeObserver);
  50055. }
  50056. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50057. },
  50058. enumerable: true,
  50059. configurable: true
  50060. });
  50061. Object.defineProperty(SpriteManager.prototype, "texture", {
  50062. get: function () {
  50063. return this._spriteTexture;
  50064. },
  50065. set: function (value) {
  50066. this._spriteTexture = value;
  50067. },
  50068. enumerable: true,
  50069. configurable: true
  50070. });
  50071. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50072. var arrayOffset = index * 16;
  50073. if (offsetX === 0)
  50074. offsetX = this._epsilon;
  50075. else if (offsetX === 1)
  50076. offsetX = 1 - this._epsilon;
  50077. if (offsetY === 0)
  50078. offsetY = this._epsilon;
  50079. else if (offsetY === 1)
  50080. offsetY = 1 - this._epsilon;
  50081. this._vertexData[arrayOffset] = sprite.position.x;
  50082. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50083. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50084. this._vertexData[arrayOffset + 3] = sprite.angle;
  50085. this._vertexData[arrayOffset + 4] = sprite.width;
  50086. this._vertexData[arrayOffset + 5] = sprite.height;
  50087. this._vertexData[arrayOffset + 6] = offsetX;
  50088. this._vertexData[arrayOffset + 7] = offsetY;
  50089. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50090. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50091. var offset = (sprite.cellIndex / rowSize) >> 0;
  50092. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50093. this._vertexData[arrayOffset + 11] = offset;
  50094. // Color
  50095. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50096. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50097. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50098. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50099. };
  50100. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50101. var count = Math.min(this._capacity, this.sprites.length);
  50102. var min = BABYLON.Vector3.Zero();
  50103. var max = BABYLON.Vector3.Zero();
  50104. var distance = Number.MAX_VALUE;
  50105. var currentSprite = null;
  50106. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50107. var cameraView = camera.getViewMatrix();
  50108. for (var index = 0; index < count; index++) {
  50109. var sprite = this.sprites[index];
  50110. if (!sprite) {
  50111. continue;
  50112. }
  50113. if (predicate) {
  50114. if (!predicate(sprite)) {
  50115. continue;
  50116. }
  50117. }
  50118. else if (!sprite.isPickable) {
  50119. continue;
  50120. }
  50121. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50122. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50123. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50124. if (ray.intersectsBoxMinMax(min, max)) {
  50125. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50126. if (distance > currentDistance) {
  50127. distance = currentDistance;
  50128. currentSprite = sprite;
  50129. if (fastCheck) {
  50130. break;
  50131. }
  50132. }
  50133. }
  50134. }
  50135. if (currentSprite) {
  50136. var result = new BABYLON.PickingInfo();
  50137. result.hit = true;
  50138. result.pickedSprite = currentSprite;
  50139. result.distance = distance;
  50140. return result;
  50141. }
  50142. return null;
  50143. };
  50144. SpriteManager.prototype.render = function () {
  50145. // Check
  50146. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50147. return;
  50148. var engine = this._scene.getEngine();
  50149. var baseSize = this._spriteTexture.getBaseSize();
  50150. // Sprites
  50151. var deltaTime = engine.getDeltaTime();
  50152. var max = Math.min(this._capacity, this.sprites.length);
  50153. var rowSize = baseSize.width / this.cellWidth;
  50154. var offset = 0;
  50155. for (var index = 0; index < max; index++) {
  50156. var sprite = this.sprites[index];
  50157. if (!sprite) {
  50158. continue;
  50159. }
  50160. sprite._animate(deltaTime);
  50161. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50162. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50163. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50164. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50165. }
  50166. this._buffer.update(this._vertexData);
  50167. // Render
  50168. var effect = this._effectBase;
  50169. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50170. effect = this._effectFog;
  50171. }
  50172. engine.enableEffect(effect);
  50173. var viewMatrix = this._scene.getViewMatrix();
  50174. effect.setTexture("diffuseSampler", this._spriteTexture);
  50175. effect.setMatrix("view", viewMatrix);
  50176. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50177. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50178. // Fog
  50179. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50180. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50181. effect.setColor3("vFogColor", this._scene.fogColor);
  50182. }
  50183. // VBOs
  50184. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50185. // Draw order
  50186. engine.setDepthFunctionToLessOrEqual();
  50187. effect.setBool("alphaTest", true);
  50188. engine.setColorWrite(false);
  50189. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50190. engine.setColorWrite(true);
  50191. effect.setBool("alphaTest", false);
  50192. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50193. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50194. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50195. };
  50196. SpriteManager.prototype.dispose = function () {
  50197. if (this._buffer) {
  50198. this._buffer.dispose();
  50199. this._buffer = null;
  50200. }
  50201. if (this._indexBuffer) {
  50202. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50203. this._indexBuffer = null;
  50204. }
  50205. if (this._spriteTexture) {
  50206. this._spriteTexture.dispose();
  50207. this._spriteTexture = null;
  50208. }
  50209. // Remove from scene
  50210. var index = this._scene.spriteManagers.indexOf(this);
  50211. this._scene.spriteManagers.splice(index, 1);
  50212. // Callback
  50213. this.onDisposeObservable.notifyObservers(this);
  50214. this.onDisposeObservable.clear();
  50215. };
  50216. return SpriteManager;
  50217. }());
  50218. BABYLON.SpriteManager = SpriteManager;
  50219. })(BABYLON || (BABYLON = {}));
  50220. //# sourceMappingURL=babylon.spriteManager.js.map
  50221. "use strict";
  50222. var BABYLON;
  50223. (function (BABYLON) {
  50224. var Sprite = /** @class */ (function () {
  50225. function Sprite(name, manager) {
  50226. this.name = name;
  50227. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50228. this.width = 1.0;
  50229. this.height = 1.0;
  50230. this.angle = 0;
  50231. this.cellIndex = 0;
  50232. this.invertU = 0;
  50233. this.invertV = 0;
  50234. this.animations = new Array();
  50235. this.isPickable = false;
  50236. this._animationStarted = false;
  50237. this._loopAnimation = false;
  50238. this._fromIndex = 0;
  50239. this._toIndex = 0;
  50240. this._delay = 0;
  50241. this._direction = 1;
  50242. this._time = 0;
  50243. this._manager = manager;
  50244. this._manager.sprites.push(this);
  50245. this.position = BABYLON.Vector3.Zero();
  50246. }
  50247. Object.defineProperty(Sprite.prototype, "size", {
  50248. get: function () {
  50249. return this.width;
  50250. },
  50251. set: function (value) {
  50252. this.width = value;
  50253. this.height = value;
  50254. },
  50255. enumerable: true,
  50256. configurable: true
  50257. });
  50258. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50259. this._fromIndex = from;
  50260. this._toIndex = to;
  50261. this._loopAnimation = loop;
  50262. this._delay = delay;
  50263. this._animationStarted = true;
  50264. this._direction = from < to ? 1 : -1;
  50265. this.cellIndex = from;
  50266. this._time = 0;
  50267. this._onAnimationEnd = onAnimationEnd;
  50268. };
  50269. Sprite.prototype.stopAnimation = function () {
  50270. this._animationStarted = false;
  50271. };
  50272. Sprite.prototype._animate = function (deltaTime) {
  50273. if (!this._animationStarted)
  50274. return;
  50275. this._time += deltaTime;
  50276. if (this._time > this._delay) {
  50277. this._time = this._time % this._delay;
  50278. this.cellIndex += this._direction;
  50279. if (this.cellIndex > this._toIndex) {
  50280. if (this._loopAnimation) {
  50281. this.cellIndex = this._fromIndex;
  50282. }
  50283. else {
  50284. this.cellIndex = this._toIndex;
  50285. this._animationStarted = false;
  50286. if (this._onAnimationEnd) {
  50287. this._onAnimationEnd();
  50288. }
  50289. if (this.disposeWhenFinishedAnimating) {
  50290. this.dispose();
  50291. }
  50292. }
  50293. }
  50294. }
  50295. };
  50296. Sprite.prototype.dispose = function () {
  50297. for (var i = 0; i < this._manager.sprites.length; i++) {
  50298. if (this._manager.sprites[i] == this) {
  50299. this._manager.sprites.splice(i, 1);
  50300. }
  50301. }
  50302. };
  50303. return Sprite;
  50304. }());
  50305. BABYLON.Sprite = Sprite;
  50306. })(BABYLON || (BABYLON = {}));
  50307. //# sourceMappingURL=babylon.sprite.js.map
  50308. "use strict";
  50309. var BABYLON;
  50310. (function (BABYLON) {
  50311. var IntersectionInfo = /** @class */ (function () {
  50312. function IntersectionInfo(bu, bv, distance) {
  50313. this.bu = bu;
  50314. this.bv = bv;
  50315. this.distance = distance;
  50316. this.faceId = 0;
  50317. this.subMeshId = 0;
  50318. }
  50319. return IntersectionInfo;
  50320. }());
  50321. BABYLON.IntersectionInfo = IntersectionInfo;
  50322. var PickingInfo = /** @class */ (function () {
  50323. function PickingInfo() {
  50324. this.hit = false;
  50325. this.distance = 0;
  50326. this.pickedPoint = null;
  50327. this.pickedMesh = null;
  50328. this.bu = 0;
  50329. this.bv = 0;
  50330. this.faceId = -1;
  50331. this.subMeshId = 0;
  50332. this.pickedSprite = null;
  50333. }
  50334. // Methods
  50335. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50336. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50337. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50338. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50339. return null;
  50340. }
  50341. var indices = this.pickedMesh.getIndices();
  50342. if (!indices) {
  50343. return null;
  50344. }
  50345. var result;
  50346. if (useVerticesNormals) {
  50347. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50348. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50349. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50350. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50351. normal0 = normal0.scale(this.bu);
  50352. normal1 = normal1.scale(this.bv);
  50353. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50354. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50355. }
  50356. else {
  50357. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50358. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50359. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50360. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50361. var p1p2 = vertex1.subtract(vertex2);
  50362. var p3p2 = vertex3.subtract(vertex2);
  50363. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50364. }
  50365. if (useWorldCoordinates) {
  50366. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50367. }
  50368. return BABYLON.Vector3.Normalize(result);
  50369. };
  50370. PickingInfo.prototype.getTextureCoordinates = function () {
  50371. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50372. return null;
  50373. }
  50374. var indices = this.pickedMesh.getIndices();
  50375. if (!indices) {
  50376. return null;
  50377. }
  50378. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50379. if (!uvs) {
  50380. return null;
  50381. }
  50382. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50383. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50384. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50385. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50386. uv1 = uv1.scale(this.bu);
  50387. uv2 = uv2.scale(this.bv);
  50388. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50389. };
  50390. return PickingInfo;
  50391. }());
  50392. BABYLON.PickingInfo = PickingInfo;
  50393. })(BABYLON || (BABYLON = {}));
  50394. //# sourceMappingURL=babylon.pickingInfo.js.map
  50395. "use strict";
  50396. var BABYLON;
  50397. (function (BABYLON) {
  50398. var Ray = /** @class */ (function () {
  50399. function Ray(origin, direction, length) {
  50400. if (length === void 0) { length = Number.MAX_VALUE; }
  50401. this.origin = origin;
  50402. this.direction = direction;
  50403. this.length = length;
  50404. }
  50405. // Methods
  50406. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50407. var d = 0.0;
  50408. var maxValue = Number.MAX_VALUE;
  50409. var inv;
  50410. var min;
  50411. var max;
  50412. var temp;
  50413. if (Math.abs(this.direction.x) < 0.0000001) {
  50414. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50415. return false;
  50416. }
  50417. }
  50418. else {
  50419. inv = 1.0 / this.direction.x;
  50420. min = (minimum.x - this.origin.x) * inv;
  50421. max = (maximum.x - this.origin.x) * inv;
  50422. if (max === -Infinity) {
  50423. max = Infinity;
  50424. }
  50425. if (min > max) {
  50426. temp = min;
  50427. min = max;
  50428. max = temp;
  50429. }
  50430. d = Math.max(min, d);
  50431. maxValue = Math.min(max, maxValue);
  50432. if (d > maxValue) {
  50433. return false;
  50434. }
  50435. }
  50436. if (Math.abs(this.direction.y) < 0.0000001) {
  50437. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50438. return false;
  50439. }
  50440. }
  50441. else {
  50442. inv = 1.0 / this.direction.y;
  50443. min = (minimum.y - this.origin.y) * inv;
  50444. max = (maximum.y - this.origin.y) * inv;
  50445. if (max === -Infinity) {
  50446. max = Infinity;
  50447. }
  50448. if (min > max) {
  50449. temp = min;
  50450. min = max;
  50451. max = temp;
  50452. }
  50453. d = Math.max(min, d);
  50454. maxValue = Math.min(max, maxValue);
  50455. if (d > maxValue) {
  50456. return false;
  50457. }
  50458. }
  50459. if (Math.abs(this.direction.z) < 0.0000001) {
  50460. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50461. return false;
  50462. }
  50463. }
  50464. else {
  50465. inv = 1.0 / this.direction.z;
  50466. min = (minimum.z - this.origin.z) * inv;
  50467. max = (maximum.z - this.origin.z) * inv;
  50468. if (max === -Infinity) {
  50469. max = Infinity;
  50470. }
  50471. if (min > max) {
  50472. temp = min;
  50473. min = max;
  50474. max = temp;
  50475. }
  50476. d = Math.max(min, d);
  50477. maxValue = Math.min(max, maxValue);
  50478. if (d > maxValue) {
  50479. return false;
  50480. }
  50481. }
  50482. return true;
  50483. };
  50484. Ray.prototype.intersectsBox = function (box) {
  50485. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50486. };
  50487. Ray.prototype.intersectsSphere = function (sphere) {
  50488. var x = sphere.center.x - this.origin.x;
  50489. var y = sphere.center.y - this.origin.y;
  50490. var z = sphere.center.z - this.origin.z;
  50491. var pyth = (x * x) + (y * y) + (z * z);
  50492. var rr = sphere.radius * sphere.radius;
  50493. if (pyth <= rr) {
  50494. return true;
  50495. }
  50496. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50497. if (dot < 0.0) {
  50498. return false;
  50499. }
  50500. var temp = pyth - (dot * dot);
  50501. return temp <= rr;
  50502. };
  50503. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50504. if (!this._edge1) {
  50505. this._edge1 = BABYLON.Vector3.Zero();
  50506. this._edge2 = BABYLON.Vector3.Zero();
  50507. this._pvec = BABYLON.Vector3.Zero();
  50508. this._tvec = BABYLON.Vector3.Zero();
  50509. this._qvec = BABYLON.Vector3.Zero();
  50510. }
  50511. vertex1.subtractToRef(vertex0, this._edge1);
  50512. vertex2.subtractToRef(vertex0, this._edge2);
  50513. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50514. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50515. if (det === 0) {
  50516. return null;
  50517. }
  50518. var invdet = 1 / det;
  50519. this.origin.subtractToRef(vertex0, this._tvec);
  50520. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50521. if (bu < 0 || bu > 1.0) {
  50522. return null;
  50523. }
  50524. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50525. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50526. if (bv < 0 || bu + bv > 1.0) {
  50527. return null;
  50528. }
  50529. //check if the distance is longer than the predefined length.
  50530. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50531. if (distance > this.length) {
  50532. return null;
  50533. }
  50534. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50535. };
  50536. Ray.prototype.intersectsPlane = function (plane) {
  50537. var distance;
  50538. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50539. if (Math.abs(result1) < 9.99999997475243E-07) {
  50540. return null;
  50541. }
  50542. else {
  50543. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50544. distance = (-plane.d - result2) / result1;
  50545. if (distance < 0.0) {
  50546. if (distance < -9.99999997475243E-07) {
  50547. return null;
  50548. }
  50549. else {
  50550. return 0;
  50551. }
  50552. }
  50553. return distance;
  50554. }
  50555. };
  50556. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50557. var tm = BABYLON.Tmp.Matrix[0];
  50558. mesh.getWorldMatrix().invertToRef(tm);
  50559. if (this._tmpRay) {
  50560. Ray.TransformToRef(this, tm, this._tmpRay);
  50561. }
  50562. else {
  50563. this._tmpRay = Ray.Transform(this, tm);
  50564. }
  50565. return mesh.intersects(this._tmpRay, fastCheck);
  50566. };
  50567. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50568. if (results) {
  50569. results.length = 0;
  50570. }
  50571. else {
  50572. results = [];
  50573. }
  50574. for (var i = 0; i < meshes.length; i++) {
  50575. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50576. if (pickInfo.hit) {
  50577. results.push(pickInfo);
  50578. }
  50579. }
  50580. results.sort(this._comparePickingInfo);
  50581. return results;
  50582. };
  50583. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50584. if (pickingInfoA.distance < pickingInfoB.distance) {
  50585. return -1;
  50586. }
  50587. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50588. return 1;
  50589. }
  50590. else {
  50591. return 0;
  50592. }
  50593. };
  50594. /**
  50595. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50596. * @param sega the first point of the segment to test the intersection against
  50597. * @param segb the second point of the segment to test the intersection against
  50598. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50599. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50600. */
  50601. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50602. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50603. var u = segb.subtract(sega);
  50604. var v = rsegb.subtract(this.origin);
  50605. var w = sega.subtract(this.origin);
  50606. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50607. var b = BABYLON.Vector3.Dot(u, v);
  50608. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50609. var d = BABYLON.Vector3.Dot(u, w);
  50610. var e = BABYLON.Vector3.Dot(v, w);
  50611. var D = a * c - b * b; // always >= 0
  50612. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50613. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50614. // compute the line parameters of the two closest points
  50615. if (D < Ray.smallnum) {
  50616. sN = 0.0; // force using point P0 on segment S1
  50617. sD = 1.0; // to prevent possible division by 0.0 later
  50618. tN = e;
  50619. tD = c;
  50620. }
  50621. else {
  50622. sN = (b * e - c * d);
  50623. tN = (a * e - b * d);
  50624. if (sN < 0.0) {
  50625. sN = 0.0;
  50626. tN = e;
  50627. tD = c;
  50628. }
  50629. else if (sN > sD) {
  50630. sN = sD;
  50631. tN = e + b;
  50632. tD = c;
  50633. }
  50634. }
  50635. if (tN < 0.0) {
  50636. tN = 0.0;
  50637. // recompute sc for this edge
  50638. if (-d < 0.0) {
  50639. sN = 0.0;
  50640. }
  50641. else if (-d > a)
  50642. sN = sD;
  50643. else {
  50644. sN = -d;
  50645. sD = a;
  50646. }
  50647. }
  50648. else if (tN > tD) {
  50649. tN = tD;
  50650. // recompute sc for this edge
  50651. if ((-d + b) < 0.0) {
  50652. sN = 0;
  50653. }
  50654. else if ((-d + b) > a) {
  50655. sN = sD;
  50656. }
  50657. else {
  50658. sN = (-d + b);
  50659. sD = a;
  50660. }
  50661. }
  50662. // finally do the division to get sc and tc
  50663. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50664. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50665. // get the difference of the two closest points
  50666. var qtc = v.multiplyByFloats(tc, tc, tc);
  50667. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50668. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50669. if (isIntersected) {
  50670. return qtc.length();
  50671. }
  50672. return -1;
  50673. };
  50674. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50675. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50676. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50677. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50678. this.direction.normalize();
  50679. return this;
  50680. };
  50681. // Statics
  50682. Ray.Zero = function () {
  50683. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50684. };
  50685. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50686. var result = Ray.Zero();
  50687. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50688. };
  50689. /**
  50690. * 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
  50691. * transformed to the given world matrix.
  50692. * @param origin The origin point
  50693. * @param end The end point
  50694. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50695. */
  50696. Ray.CreateNewFromTo = function (origin, end, world) {
  50697. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50698. var direction = end.subtract(origin);
  50699. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50700. direction.normalize();
  50701. return Ray.Transform(new Ray(origin, direction, length), world);
  50702. };
  50703. Ray.Transform = function (ray, matrix) {
  50704. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50705. Ray.TransformToRef(ray, matrix, result);
  50706. return result;
  50707. };
  50708. Ray.TransformToRef = function (ray, matrix, result) {
  50709. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50710. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50711. result.length = ray.length;
  50712. var dir = result.direction;
  50713. var len = dir.length();
  50714. if (!(len === 0 || len === 1)) {
  50715. var num = 1.0 / len;
  50716. dir.x *= num;
  50717. dir.y *= num;
  50718. dir.z *= num;
  50719. result.length *= len;
  50720. }
  50721. };
  50722. Ray.smallnum = 0.00000001;
  50723. Ray.rayl = 10e8;
  50724. return Ray;
  50725. }());
  50726. BABYLON.Ray = Ray;
  50727. })(BABYLON || (BABYLON = {}));
  50728. //# sourceMappingURL=babylon.ray.js.map
  50729. "use strict";
  50730. var BABYLON;
  50731. (function (BABYLON) {
  50732. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50733. if (boxMin.x > sphereCenter.x + sphereRadius)
  50734. return false;
  50735. if (sphereCenter.x - sphereRadius > boxMax.x)
  50736. return false;
  50737. if (boxMin.y > sphereCenter.y + sphereRadius)
  50738. return false;
  50739. if (sphereCenter.y - sphereRadius > boxMax.y)
  50740. return false;
  50741. if (boxMin.z > sphereCenter.z + sphereRadius)
  50742. return false;
  50743. if (sphereCenter.z - sphereRadius > boxMax.z)
  50744. return false;
  50745. return true;
  50746. };
  50747. var getLowestRoot = (function () {
  50748. var result = { root: 0, found: false };
  50749. return function (a, b, c, maxR) {
  50750. result.root = 0;
  50751. result.found = false;
  50752. var determinant = b * b - 4.0 * a * c;
  50753. if (determinant < 0)
  50754. return result;
  50755. var sqrtD = Math.sqrt(determinant);
  50756. var r1 = (-b - sqrtD) / (2.0 * a);
  50757. var r2 = (-b + sqrtD) / (2.0 * a);
  50758. if (r1 > r2) {
  50759. var temp = r2;
  50760. r2 = r1;
  50761. r1 = temp;
  50762. }
  50763. if (r1 > 0 && r1 < maxR) {
  50764. result.root = r1;
  50765. result.found = true;
  50766. return result;
  50767. }
  50768. if (r2 > 0 && r2 < maxR) {
  50769. result.root = r2;
  50770. result.found = true;
  50771. return result;
  50772. }
  50773. return result;
  50774. };
  50775. })();
  50776. var Collider = /** @class */ (function () {
  50777. function Collider() {
  50778. this._collisionPoint = BABYLON.Vector3.Zero();
  50779. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50780. this._tempVector = BABYLON.Vector3.Zero();
  50781. this._tempVector2 = BABYLON.Vector3.Zero();
  50782. this._tempVector3 = BABYLON.Vector3.Zero();
  50783. this._tempVector4 = BABYLON.Vector3.Zero();
  50784. this._edge = BABYLON.Vector3.Zero();
  50785. this._baseToVertex = BABYLON.Vector3.Zero();
  50786. this._destinationPoint = BABYLON.Vector3.Zero();
  50787. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50788. this._displacementVector = BABYLON.Vector3.Zero();
  50789. this._radius = BABYLON.Vector3.One();
  50790. this._retry = 0;
  50791. this._basePointWorld = BABYLON.Vector3.Zero();
  50792. this._velocityWorld = BABYLON.Vector3.Zero();
  50793. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50794. this._collisionMask = -1;
  50795. }
  50796. Object.defineProperty(Collider.prototype, "collisionMask", {
  50797. get: function () {
  50798. return this._collisionMask;
  50799. },
  50800. set: function (mask) {
  50801. this._collisionMask = !isNaN(mask) ? mask : -1;
  50802. },
  50803. enumerable: true,
  50804. configurable: true
  50805. });
  50806. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50807. /**
  50808. * Gets the plane normal used to compute the sliding response (in local space)
  50809. */
  50810. get: function () {
  50811. return this._slidePlaneNormal;
  50812. },
  50813. enumerable: true,
  50814. configurable: true
  50815. });
  50816. // Methods
  50817. Collider.prototype._initialize = function (source, dir, e) {
  50818. this._velocity = dir;
  50819. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50820. this._basePoint = source;
  50821. source.multiplyToRef(this._radius, this._basePointWorld);
  50822. dir.multiplyToRef(this._radius, this._velocityWorld);
  50823. this._velocityWorldLength = this._velocityWorld.length();
  50824. this._epsilon = e;
  50825. this.collisionFound = false;
  50826. };
  50827. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50828. pa.subtractToRef(point, this._tempVector);
  50829. pb.subtractToRef(point, this._tempVector2);
  50830. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50831. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50832. if (d < 0)
  50833. return false;
  50834. pc.subtractToRef(point, this._tempVector3);
  50835. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50836. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50837. if (d < 0)
  50838. return false;
  50839. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50840. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50841. return d >= 0;
  50842. };
  50843. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50844. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50845. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50846. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50847. return false;
  50848. }
  50849. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50850. return false;
  50851. return true;
  50852. };
  50853. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50854. var t0;
  50855. var embeddedInPlane = false;
  50856. //defensive programming, actually not needed.
  50857. if (!trianglePlaneArray) {
  50858. trianglePlaneArray = [];
  50859. }
  50860. if (!trianglePlaneArray[faceIndex]) {
  50861. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50862. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50863. }
  50864. var trianglePlane = trianglePlaneArray[faceIndex];
  50865. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50866. return;
  50867. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50868. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50869. if (normalDotVelocity == 0) {
  50870. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50871. return;
  50872. embeddedInPlane = true;
  50873. t0 = 0;
  50874. }
  50875. else {
  50876. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50877. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50878. if (t0 > t1) {
  50879. var temp = t1;
  50880. t1 = t0;
  50881. t0 = temp;
  50882. }
  50883. if (t0 > 1.0 || t1 < 0.0)
  50884. return;
  50885. if (t0 < 0)
  50886. t0 = 0;
  50887. if (t0 > 1.0)
  50888. t0 = 1.0;
  50889. }
  50890. this._collisionPoint.copyFromFloats(0, 0, 0);
  50891. var found = false;
  50892. var t = 1.0;
  50893. if (!embeddedInPlane) {
  50894. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50895. this._velocity.scaleToRef(t0, this._tempVector);
  50896. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50897. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50898. found = true;
  50899. t = t0;
  50900. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50901. }
  50902. }
  50903. if (!found) {
  50904. var velocitySquaredLength = this._velocity.lengthSquared();
  50905. var a = velocitySquaredLength;
  50906. this._basePoint.subtractToRef(p1, this._tempVector);
  50907. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50908. var c = this._tempVector.lengthSquared() - 1.0;
  50909. var lowestRoot = getLowestRoot(a, b, c, t);
  50910. if (lowestRoot.found) {
  50911. t = lowestRoot.root;
  50912. found = true;
  50913. this._collisionPoint.copyFrom(p1);
  50914. }
  50915. this._basePoint.subtractToRef(p2, this._tempVector);
  50916. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50917. c = this._tempVector.lengthSquared() - 1.0;
  50918. lowestRoot = getLowestRoot(a, b, c, t);
  50919. if (lowestRoot.found) {
  50920. t = lowestRoot.root;
  50921. found = true;
  50922. this._collisionPoint.copyFrom(p2);
  50923. }
  50924. this._basePoint.subtractToRef(p3, this._tempVector);
  50925. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50926. c = this._tempVector.lengthSquared() - 1.0;
  50927. lowestRoot = getLowestRoot(a, b, c, t);
  50928. if (lowestRoot.found) {
  50929. t = lowestRoot.root;
  50930. found = true;
  50931. this._collisionPoint.copyFrom(p3);
  50932. }
  50933. p2.subtractToRef(p1, this._edge);
  50934. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50935. var edgeSquaredLength = this._edge.lengthSquared();
  50936. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50937. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50938. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50939. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50940. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50941. lowestRoot = getLowestRoot(a, b, c, t);
  50942. if (lowestRoot.found) {
  50943. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50944. if (f >= 0.0 && f <= 1.0) {
  50945. t = lowestRoot.root;
  50946. found = true;
  50947. this._edge.scaleInPlace(f);
  50948. p1.addToRef(this._edge, this._collisionPoint);
  50949. }
  50950. }
  50951. p3.subtractToRef(p2, this._edge);
  50952. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50953. edgeSquaredLength = this._edge.lengthSquared();
  50954. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50955. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50956. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50957. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50958. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50959. lowestRoot = getLowestRoot(a, b, c, t);
  50960. if (lowestRoot.found) {
  50961. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50962. if (f >= 0.0 && f <= 1.0) {
  50963. t = lowestRoot.root;
  50964. found = true;
  50965. this._edge.scaleInPlace(f);
  50966. p2.addToRef(this._edge, this._collisionPoint);
  50967. }
  50968. }
  50969. p1.subtractToRef(p3, this._edge);
  50970. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50971. edgeSquaredLength = this._edge.lengthSquared();
  50972. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50973. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50974. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50975. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50976. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50977. lowestRoot = getLowestRoot(a, b, c, t);
  50978. if (lowestRoot.found) {
  50979. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50980. if (f >= 0.0 && f <= 1.0) {
  50981. t = lowestRoot.root;
  50982. found = true;
  50983. this._edge.scaleInPlace(f);
  50984. p3.addToRef(this._edge, this._collisionPoint);
  50985. }
  50986. }
  50987. }
  50988. if (found) {
  50989. var distToCollision = t * this._velocity.length();
  50990. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50991. if (!this.intersectionPoint) {
  50992. this.intersectionPoint = this._collisionPoint.clone();
  50993. }
  50994. else {
  50995. this.intersectionPoint.copyFrom(this._collisionPoint);
  50996. }
  50997. this._nearestDistance = distToCollision;
  50998. this.collisionFound = true;
  50999. }
  51000. }
  51001. };
  51002. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51003. for (var i = indexStart; i < indexEnd; i += 3) {
  51004. var p1 = pts[indices[i] - decal];
  51005. var p2 = pts[indices[i + 1] - decal];
  51006. var p3 = pts[indices[i + 2] - decal];
  51007. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51008. }
  51009. };
  51010. Collider.prototype._getResponse = function (pos, vel) {
  51011. pos.addToRef(vel, this._destinationPoint);
  51012. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51013. this._basePoint.addToRef(vel, pos);
  51014. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51015. this._slidePlaneNormal.normalize();
  51016. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51017. pos.addInPlace(this._displacementVector);
  51018. this.intersectionPoint.addInPlace(this._displacementVector);
  51019. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51020. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51021. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51022. };
  51023. return Collider;
  51024. }());
  51025. BABYLON.Collider = Collider;
  51026. })(BABYLON || (BABYLON = {}));
  51027. //# sourceMappingURL=babylon.collider.js.map
  51028. "use strict";
  51029. var BABYLON;
  51030. (function (BABYLON) {
  51031. //WebWorker code will be inserted to this variable.
  51032. BABYLON.CollisionWorker = "";
  51033. var WorkerTaskType;
  51034. (function (WorkerTaskType) {
  51035. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51036. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51037. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51038. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51039. var WorkerReplyType;
  51040. (function (WorkerReplyType) {
  51041. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51042. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51043. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51044. var CollisionCoordinatorWorker = /** @class */ (function () {
  51045. function CollisionCoordinatorWorker() {
  51046. var _this = this;
  51047. this._scaledPosition = BABYLON.Vector3.Zero();
  51048. this._scaledVelocity = BABYLON.Vector3.Zero();
  51049. this.onMeshUpdated = function (transformNode) {
  51050. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51051. };
  51052. this.onGeometryUpdated = function (geometry) {
  51053. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51054. };
  51055. this._afterRender = function () {
  51056. if (!_this._init)
  51057. return;
  51058. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51059. return;
  51060. }
  51061. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51062. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51063. if (_this._runningUpdated > 4) {
  51064. return;
  51065. }
  51066. ++_this._runningUpdated;
  51067. var payload = {
  51068. updatedMeshes: _this._addUpdateMeshesList,
  51069. updatedGeometries: _this._addUpdateGeometriesList,
  51070. removedGeometries: _this._toRemoveGeometryArray,
  51071. removedMeshes: _this._toRemoveMeshesArray
  51072. };
  51073. var message = {
  51074. payload: payload,
  51075. taskType: WorkerTaskType.UPDATE
  51076. };
  51077. var serializable = [];
  51078. for (var id in payload.updatedGeometries) {
  51079. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51080. //prepare transferables
  51081. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51082. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51083. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51084. }
  51085. }
  51086. _this._worker.postMessage(message, serializable);
  51087. _this._addUpdateMeshesList = {};
  51088. _this._addUpdateGeometriesList = {};
  51089. _this._toRemoveGeometryArray = [];
  51090. _this._toRemoveMeshesArray = [];
  51091. };
  51092. this._onMessageFromWorker = function (e) {
  51093. var returnData = e.data;
  51094. if (returnData.error != WorkerReplyType.SUCCESS) {
  51095. //TODO what errors can be returned from the worker?
  51096. BABYLON.Tools.Warn("error returned from worker!");
  51097. return;
  51098. }
  51099. switch (returnData.taskType) {
  51100. case WorkerTaskType.INIT:
  51101. _this._init = true;
  51102. //Update the worked with ALL of the scene's current state
  51103. _this._scene.meshes.forEach(function (mesh) {
  51104. _this.onMeshAdded(mesh);
  51105. });
  51106. _this._scene.getGeometries().forEach(function (geometry) {
  51107. _this.onGeometryAdded(geometry);
  51108. });
  51109. break;
  51110. case WorkerTaskType.UPDATE:
  51111. _this._runningUpdated--;
  51112. break;
  51113. case WorkerTaskType.COLLIDE:
  51114. var returnPayload = returnData.payload;
  51115. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51116. return;
  51117. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51118. if (callback) {
  51119. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51120. if (mesh) {
  51121. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51122. }
  51123. }
  51124. //cleanup
  51125. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51126. break;
  51127. }
  51128. };
  51129. this._collisionsCallbackArray = [];
  51130. this._init = false;
  51131. this._runningUpdated = 0;
  51132. this._addUpdateMeshesList = {};
  51133. this._addUpdateGeometriesList = {};
  51134. this._toRemoveGeometryArray = [];
  51135. this._toRemoveMeshesArray = [];
  51136. }
  51137. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51138. if (!this._init)
  51139. return;
  51140. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51141. return;
  51142. position.divideToRef(collider._radius, this._scaledPosition);
  51143. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51144. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51145. var payload = {
  51146. collider: {
  51147. position: this._scaledPosition.asArray(),
  51148. velocity: this._scaledVelocity.asArray(),
  51149. radius: collider._radius.asArray()
  51150. },
  51151. collisionId: collisionIndex,
  51152. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51153. maximumRetry: maximumRetry
  51154. };
  51155. var message = {
  51156. payload: payload,
  51157. taskType: WorkerTaskType.COLLIDE
  51158. };
  51159. this._worker.postMessage(message);
  51160. };
  51161. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51162. this._scene = scene;
  51163. this._scene.registerAfterRender(this._afterRender);
  51164. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51165. this._worker = new Worker(workerUrl);
  51166. this._worker.onmessage = this._onMessageFromWorker;
  51167. var message = {
  51168. payload: {},
  51169. taskType: WorkerTaskType.INIT
  51170. };
  51171. this._worker.postMessage(message);
  51172. };
  51173. CollisionCoordinatorWorker.prototype.destroy = function () {
  51174. this._scene.unregisterAfterRender(this._afterRender);
  51175. this._worker.terminate();
  51176. };
  51177. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51178. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51179. this.onMeshUpdated(mesh);
  51180. };
  51181. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51182. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51183. };
  51184. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51185. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51186. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51187. this.onGeometryUpdated(geometry);
  51188. };
  51189. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51190. this._toRemoveGeometryArray.push(geometry.id);
  51191. };
  51192. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51193. var submeshes = [];
  51194. if (mesh.subMeshes) {
  51195. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51196. var boundingInfo = sm.getBoundingInfo();
  51197. return {
  51198. position: idx,
  51199. verticesStart: sm.verticesStart,
  51200. verticesCount: sm.verticesCount,
  51201. indexStart: sm.indexStart,
  51202. indexCount: sm.indexCount,
  51203. hasMaterial: !!sm.getMaterial(),
  51204. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51205. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51206. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51207. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51208. };
  51209. });
  51210. }
  51211. var geometryId = null;
  51212. if (mesh instanceof BABYLON.Mesh) {
  51213. var geometry = mesh.geometry;
  51214. geometryId = geometry ? geometry.id : null;
  51215. }
  51216. else if (mesh instanceof BABYLON.InstancedMesh) {
  51217. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51218. geometryId = geometry ? geometry.id : null;
  51219. }
  51220. var boundingInfo = mesh.getBoundingInfo();
  51221. return {
  51222. uniqueId: mesh.uniqueId,
  51223. id: mesh.id,
  51224. name: mesh.name,
  51225. geometryId: geometryId,
  51226. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51227. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51228. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51229. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51230. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51231. subMeshes: submeshes,
  51232. checkCollisions: mesh.checkCollisions
  51233. };
  51234. };
  51235. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51236. return {
  51237. id: geometry.id,
  51238. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51239. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51240. indices: new Uint32Array(geometry.getIndices() || []),
  51241. };
  51242. };
  51243. return CollisionCoordinatorWorker;
  51244. }());
  51245. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51246. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51247. function CollisionCoordinatorLegacy() {
  51248. this._scaledPosition = BABYLON.Vector3.Zero();
  51249. this._scaledVelocity = BABYLON.Vector3.Zero();
  51250. this._finalPosition = BABYLON.Vector3.Zero();
  51251. }
  51252. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51253. position.divideToRef(collider._radius, this._scaledPosition);
  51254. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51255. collider.collidedMesh = null;
  51256. collider._retry = 0;
  51257. collider._initialVelocity = this._scaledVelocity;
  51258. collider._initialPosition = this._scaledPosition;
  51259. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51260. this._finalPosition.multiplyInPlace(collider._radius);
  51261. //run the callback
  51262. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51263. };
  51264. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51265. this._scene = scene;
  51266. };
  51267. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51268. //Legacy need no destruction method.
  51269. };
  51270. //No update in legacy mode
  51271. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51272. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51273. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51274. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51275. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51276. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51277. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51278. if (excludedMesh === void 0) { excludedMesh = null; }
  51279. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51280. if (collider._retry >= maximumRetry) {
  51281. finalPosition.copyFrom(position);
  51282. return;
  51283. }
  51284. // Check if this is a mesh else camera or -1
  51285. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51286. collider._initialize(position, velocity, closeDistance);
  51287. // Check all meshes
  51288. for (var index = 0; index < this._scene.meshes.length; index++) {
  51289. var mesh = this._scene.meshes[index];
  51290. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51291. mesh._checkCollision(collider);
  51292. }
  51293. }
  51294. if (!collider.collisionFound) {
  51295. position.addToRef(velocity, finalPosition);
  51296. return;
  51297. }
  51298. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51299. collider._getResponse(position, velocity);
  51300. }
  51301. if (velocity.length() <= closeDistance) {
  51302. finalPosition.copyFrom(position);
  51303. return;
  51304. }
  51305. collider._retry++;
  51306. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51307. };
  51308. return CollisionCoordinatorLegacy;
  51309. }());
  51310. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51311. })(BABYLON || (BABYLON = {}));
  51312. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51313. "use strict";
  51314. var BABYLON;
  51315. (function (BABYLON) {
  51316. /**
  51317. * A particle represents one of the element emitted by a particle system.
  51318. * This is mainly define by its coordinates, direction, velocity and age.
  51319. */
  51320. var Particle = /** @class */ (function () {
  51321. /**
  51322. * Creates a new instance of @see Particle
  51323. * @param particleSystem the particle system the particle belongs to
  51324. */
  51325. function Particle(
  51326. /**
  51327. * particleSystem the particle system the particle belongs to.
  51328. */
  51329. particleSystem) {
  51330. this.particleSystem = particleSystem;
  51331. /**
  51332. * The world position of the particle in the scene.
  51333. */
  51334. this.position = BABYLON.Vector3.Zero();
  51335. /**
  51336. * The world direction of the particle in the scene.
  51337. */
  51338. this.direction = BABYLON.Vector3.Zero();
  51339. /**
  51340. * The color of the particle.
  51341. */
  51342. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51343. /**
  51344. * The color change of the particle per step.
  51345. */
  51346. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51347. /**
  51348. * Defines how long will the life of the particle be.
  51349. */
  51350. this.lifeTime = 1.0;
  51351. /**
  51352. * The current age of the particle.
  51353. */
  51354. this.age = 0;
  51355. /**
  51356. * The current size of the particle.
  51357. */
  51358. this.size = 0;
  51359. /**
  51360. * The current angle of the particle.
  51361. */
  51362. this.angle = 0;
  51363. /**
  51364. * Defines how fast is the angle changing.
  51365. */
  51366. this.angularSpeed = 0;
  51367. /**
  51368. * Defines the cell index used by the particle to be rendered from a sprite.
  51369. */
  51370. this.cellIndex = 0;
  51371. this._currentFrameCounter = 0;
  51372. if (!this.particleSystem.isAnimationSheetEnabled) {
  51373. return;
  51374. }
  51375. this.updateCellInfoFromSystem();
  51376. }
  51377. Particle.prototype.updateCellInfoFromSystem = function () {
  51378. this.cellIndex = this.particleSystem.startSpriteCellID;
  51379. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51380. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51381. }
  51382. else {
  51383. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51384. }
  51385. };
  51386. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51387. // (ageOffset / scaledUpdateSpeed) / available cells
  51388. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51389. this._currentFrameCounter += scaledUpdateSpeed;
  51390. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51391. this._currentFrameCounter = 0;
  51392. this.cellIndex++;
  51393. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51394. this.cellIndex = this.particleSystem.endSpriteCellID;
  51395. }
  51396. }
  51397. };
  51398. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51399. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51400. this.cellIndex++;
  51401. this._currentFrameCounter = 0;
  51402. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51403. if (this.particleSystem.spriteCellLoop) {
  51404. this.cellIndex = this.particleSystem.startSpriteCellID;
  51405. }
  51406. else {
  51407. this.cellIndex = this.particleSystem.endSpriteCellID;
  51408. }
  51409. }
  51410. }
  51411. else {
  51412. this._currentFrameCounter++;
  51413. }
  51414. };
  51415. /**
  51416. * Copy the properties of particle to another one.
  51417. * @param other the particle to copy the information to.
  51418. */
  51419. Particle.prototype.copyTo = function (other) {
  51420. other.position.copyFrom(this.position);
  51421. other.direction.copyFrom(this.direction);
  51422. other.color.copyFrom(this.color);
  51423. other.colorStep.copyFrom(this.colorStep);
  51424. other.lifeTime = this.lifeTime;
  51425. other.age = this.age;
  51426. other.size = this.size;
  51427. other.angle = this.angle;
  51428. other.angularSpeed = this.angularSpeed;
  51429. other.particleSystem = this.particleSystem;
  51430. other.cellIndex = this.cellIndex;
  51431. };
  51432. return Particle;
  51433. }());
  51434. BABYLON.Particle = Particle;
  51435. })(BABYLON || (BABYLON = {}));
  51436. //# sourceMappingURL=babylon.particle.js.map
  51437. "use strict";
  51438. var BABYLON;
  51439. (function (BABYLON) {
  51440. /**
  51441. * This represents a particle system in Babylon.
  51442. * 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.
  51443. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51444. * @example https://doc.babylonjs.com/babylon101/particles
  51445. */
  51446. var ParticleSystem = /** @class */ (function () {
  51447. /**
  51448. * Instantiates a particle system.
  51449. * 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.
  51450. * @param name The name of the particle system
  51451. * @param capacity The max number of particles alive at the same time
  51452. * @param scene The scene the particle system belongs to
  51453. * @param customEffect a custom effect used to change the way particles are rendered by default
  51454. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51455. * @param epsilon Offset used to render the particles
  51456. */
  51457. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51458. if (customEffect === void 0) { customEffect = null; }
  51459. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51460. if (epsilon === void 0) { epsilon = 0.01; }
  51461. var _this = this;
  51462. /**
  51463. * List of animations used by the particle system.
  51464. */
  51465. this.animations = [];
  51466. /**
  51467. * The rendering group used by the Particle system to chose when to render.
  51468. */
  51469. this.renderingGroupId = 0;
  51470. /**
  51471. * The emitter represents the Mesh or position we are attaching the particle system to.
  51472. */
  51473. this.emitter = null;
  51474. /**
  51475. * The maximum number of particles to emit per frame
  51476. */
  51477. this.emitRate = 10;
  51478. /**
  51479. * If you want to launch only a few particles at once, that can be done, as well.
  51480. */
  51481. this.manualEmitCount = -1;
  51482. /**
  51483. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51484. */
  51485. this.updateSpeed = 0.01;
  51486. /**
  51487. * The amount of time the particle system is running (depends of the overall update speed).
  51488. */
  51489. this.targetStopDuration = 0;
  51490. /**
  51491. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51492. */
  51493. this.disposeOnStop = false;
  51494. /**
  51495. * Minimum power of emitting particles.
  51496. */
  51497. this.minEmitPower = 1;
  51498. /**
  51499. * Maximum power of emitting particles.
  51500. */
  51501. this.maxEmitPower = 1;
  51502. /**
  51503. * Minimum life time of emitting particles.
  51504. */
  51505. this.minLifeTime = 1;
  51506. /**
  51507. * Maximum life time of emitting particles.
  51508. */
  51509. this.maxLifeTime = 1;
  51510. /**
  51511. * Minimum Size of emitting particles.
  51512. */
  51513. this.minSize = 1;
  51514. /**
  51515. * Maximum Size of emitting particles.
  51516. */
  51517. this.maxSize = 1;
  51518. /**
  51519. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51520. */
  51521. this.minAngularSpeed = 0;
  51522. /**
  51523. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51524. */
  51525. this.maxAngularSpeed = 0;
  51526. /**
  51527. * The layer mask we are rendering the particles through.
  51528. */
  51529. this.layerMask = 0x0FFFFFFF;
  51530. /**
  51531. * This can help using your own shader to render the particle system.
  51532. * The according effect will be created
  51533. */
  51534. this.customShader = null;
  51535. /**
  51536. * By default particle system starts as soon as they are created. This prevents the
  51537. * automatic start to happen and let you decide when to start emitting particles.
  51538. */
  51539. this.preventAutoStart = false;
  51540. /**
  51541. * Callback triggered when the particle animation is ending.
  51542. */
  51543. this.onAnimationEnd = null;
  51544. /**
  51545. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51546. */
  51547. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51548. /**
  51549. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51550. * to override the particles.
  51551. */
  51552. this.forceDepthWrite = false;
  51553. /**
  51554. * You can use gravity if you want to give an orientation to your particles.
  51555. */
  51556. this.gravity = BABYLON.Vector3.Zero();
  51557. /**
  51558. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51559. */
  51560. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51561. /**
  51562. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51563. */
  51564. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51565. /**
  51566. * Color the particle will have at the end of its lifetime.
  51567. */
  51568. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51569. /**
  51570. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51571. */
  51572. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51573. /**
  51574. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51575. */
  51576. this.spriteCellLoop = true;
  51577. /**
  51578. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51579. */
  51580. this.spriteCellChangeSpeed = 0;
  51581. /**
  51582. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51583. */
  51584. this.startSpriteCellID = 0;
  51585. /**
  51586. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51587. */
  51588. this.endSpriteCellID = 0;
  51589. /**
  51590. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51591. */
  51592. this.spriteCellWidth = 0;
  51593. /**
  51594. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51595. */
  51596. this.spriteCellHeight = 0;
  51597. /**
  51598. * An event triggered when the system is disposed.
  51599. */
  51600. this.onDisposeObservable = new BABYLON.Observable();
  51601. this._particles = new Array();
  51602. this._stockParticles = new Array();
  51603. this._newPartsExcess = 0;
  51604. this._vertexBuffers = {};
  51605. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51606. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51607. this._scaledDirection = BABYLON.Vector3.Zero();
  51608. this._scaledGravity = BABYLON.Vector3.Zero();
  51609. this._currentRenderId = -1;
  51610. this._started = false;
  51611. this._stopped = false;
  51612. this._actualFrame = 0;
  51613. this._vertexBufferSize = 11;
  51614. // start of sub system methods
  51615. /**
  51616. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51617. * Its lifetime will start back at 0.
  51618. */
  51619. this.recycleParticle = function (particle) {
  51620. var lastParticle = _this._particles.pop();
  51621. if (lastParticle !== particle) {
  51622. lastParticle.copyTo(particle);
  51623. }
  51624. _this._stockParticles.push(lastParticle);
  51625. };
  51626. this._createParticle = function () {
  51627. var particle;
  51628. if (_this._stockParticles.length !== 0) {
  51629. particle = _this._stockParticles.pop();
  51630. particle.age = 0;
  51631. particle.cellIndex = _this.startSpriteCellID;
  51632. }
  51633. else {
  51634. particle = new BABYLON.Particle(_this);
  51635. }
  51636. return particle;
  51637. };
  51638. this._emitFromParticle = function (particle) {
  51639. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51640. return;
  51641. }
  51642. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51643. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51644. subSystem._rootParticleSystem = _this;
  51645. _this.activeSubSystems.push(subSystem);
  51646. subSystem.start();
  51647. };
  51648. this._appendParticleVertexes = null;
  51649. this.id = name;
  51650. this.name = name;
  51651. this._capacity = capacity;
  51652. this._epsilon = epsilon;
  51653. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51654. if (isAnimationSheetEnabled) {
  51655. this._vertexBufferSize = 12;
  51656. }
  51657. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51658. this._customEffect = customEffect;
  51659. scene.particleSystems.push(this);
  51660. this._createIndexBuffer();
  51661. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51662. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51663. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51664. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51665. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51666. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51667. if (this._isAnimationSheetEnabled) {
  51668. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51669. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51670. }
  51671. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51672. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51673. this._vertexBuffers["options"] = options;
  51674. // Default emitter type
  51675. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51676. this.updateFunction = function (particles) {
  51677. for (var index = 0; index < particles.length; index++) {
  51678. var particle = particles[index];
  51679. particle.age += _this._scaledUpdateSpeed;
  51680. if (particle.age >= particle.lifeTime) {
  51681. _this._emitFromParticle(particle);
  51682. _this.recycleParticle(particle);
  51683. index--;
  51684. continue;
  51685. }
  51686. else {
  51687. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51688. particle.color.addInPlace(_this._scaledColorStep);
  51689. if (particle.color.a < 0)
  51690. particle.color.a = 0;
  51691. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51692. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51693. particle.position.addInPlace(_this._scaledDirection);
  51694. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51695. particle.direction.addInPlace(_this._scaledGravity);
  51696. if (_this._isAnimationSheetEnabled) {
  51697. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51698. }
  51699. }
  51700. }
  51701. };
  51702. }
  51703. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51704. /**
  51705. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51706. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51707. */
  51708. get: function () {
  51709. if (this.particleEmitterType.direction1) {
  51710. return this.particleEmitterType.direction1;
  51711. }
  51712. return BABYLON.Vector3.Zero();
  51713. },
  51714. set: function (value) {
  51715. if (this.particleEmitterType.direction1) {
  51716. this.particleEmitterType.direction1 = value;
  51717. }
  51718. },
  51719. enumerable: true,
  51720. configurable: true
  51721. });
  51722. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51723. /**
  51724. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51725. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51726. */
  51727. get: function () {
  51728. if (this.particleEmitterType.direction2) {
  51729. return this.particleEmitterType.direction2;
  51730. }
  51731. return BABYLON.Vector3.Zero();
  51732. },
  51733. set: function (value) {
  51734. if (this.particleEmitterType.direction2) {
  51735. this.particleEmitterType.direction2 = value;
  51736. }
  51737. },
  51738. enumerable: true,
  51739. configurable: true
  51740. });
  51741. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51742. /**
  51743. * 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.
  51744. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51745. */
  51746. get: function () {
  51747. if (this.particleEmitterType.minEmitBox) {
  51748. return this.particleEmitterType.minEmitBox;
  51749. }
  51750. return BABYLON.Vector3.Zero();
  51751. },
  51752. set: function (value) {
  51753. if (this.particleEmitterType.minEmitBox) {
  51754. this.particleEmitterType.minEmitBox = value;
  51755. }
  51756. },
  51757. enumerable: true,
  51758. configurable: true
  51759. });
  51760. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51761. /**
  51762. * 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.
  51763. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51764. */
  51765. get: function () {
  51766. if (this.particleEmitterType.maxEmitBox) {
  51767. return this.particleEmitterType.maxEmitBox;
  51768. }
  51769. return BABYLON.Vector3.Zero();
  51770. },
  51771. set: function (value) {
  51772. if (this.particleEmitterType.maxEmitBox) {
  51773. this.particleEmitterType.maxEmitBox = value;
  51774. }
  51775. },
  51776. enumerable: true,
  51777. configurable: true
  51778. });
  51779. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51780. /**
  51781. * Sets a callback that will be triggered when the system is disposed.
  51782. */
  51783. set: function (callback) {
  51784. if (this._onDisposeObserver) {
  51785. this.onDisposeObservable.remove(this._onDisposeObserver);
  51786. }
  51787. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51788. },
  51789. enumerable: true,
  51790. configurable: true
  51791. });
  51792. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51793. /**
  51794. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51795. */
  51796. get: function () {
  51797. return this._isAnimationSheetEnabled;
  51798. },
  51799. enumerable: true,
  51800. configurable: true
  51801. });
  51802. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51803. //end of Sub-emitter
  51804. /**
  51805. * Gets the current list of active particles
  51806. */
  51807. get: function () {
  51808. return this._particles;
  51809. },
  51810. enumerable: true,
  51811. configurable: true
  51812. });
  51813. /**
  51814. * Returns the string "ParticleSystem"
  51815. * @returns a string containing the class name
  51816. */
  51817. ParticleSystem.prototype.getClassName = function () {
  51818. return "ParticleSystem";
  51819. };
  51820. ParticleSystem.prototype._createIndexBuffer = function () {
  51821. var indices = [];
  51822. var index = 0;
  51823. for (var count = 0; count < this._capacity; count++) {
  51824. indices.push(index);
  51825. indices.push(index + 1);
  51826. indices.push(index + 2);
  51827. indices.push(index);
  51828. indices.push(index + 2);
  51829. indices.push(index + 3);
  51830. index += 4;
  51831. }
  51832. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51833. };
  51834. /**
  51835. * Gets the maximum number of particles active at the same time.
  51836. * @returns The max number of active particles.
  51837. */
  51838. ParticleSystem.prototype.getCapacity = function () {
  51839. return this._capacity;
  51840. };
  51841. /**
  51842. * Gets Wether there are still active particles in the system.
  51843. * @returns True if it is alive, otherwise false.
  51844. */
  51845. ParticleSystem.prototype.isAlive = function () {
  51846. return this._alive;
  51847. };
  51848. /**
  51849. * Gets Wether the system has been started.
  51850. * @returns True if it has been started, otherwise false.
  51851. */
  51852. ParticleSystem.prototype.isStarted = function () {
  51853. return this._started;
  51854. };
  51855. /**
  51856. * Starts the particle system and begins to emit.
  51857. */
  51858. ParticleSystem.prototype.start = function () {
  51859. this._started = true;
  51860. this._stopped = false;
  51861. this._actualFrame = 0;
  51862. if (this.subEmitters && this.subEmitters.length != 0) {
  51863. this.activeSubSystems = new Array();
  51864. }
  51865. };
  51866. /**
  51867. * Stops the particle system.
  51868. * @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.
  51869. */
  51870. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51871. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51872. this._stopped = true;
  51873. if (stopSubEmitters) {
  51874. this._stopSubEmitters();
  51875. }
  51876. };
  51877. // animation sheet
  51878. /**
  51879. * Remove all active particles
  51880. */
  51881. ParticleSystem.prototype.reset = function () {
  51882. this._stockParticles = [];
  51883. this._particles = [];
  51884. };
  51885. /**
  51886. * @ignore (for internal use only)
  51887. */
  51888. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51889. var offset = index * this._vertexBufferSize;
  51890. this._vertexData[offset] = particle.position.x;
  51891. this._vertexData[offset + 1] = particle.position.y;
  51892. this._vertexData[offset + 2] = particle.position.z;
  51893. this._vertexData[offset + 3] = particle.color.r;
  51894. this._vertexData[offset + 4] = particle.color.g;
  51895. this._vertexData[offset + 5] = particle.color.b;
  51896. this._vertexData[offset + 6] = particle.color.a;
  51897. this._vertexData[offset + 7] = particle.angle;
  51898. this._vertexData[offset + 8] = particle.size;
  51899. this._vertexData[offset + 9] = offsetX;
  51900. this._vertexData[offset + 10] = offsetY;
  51901. };
  51902. /**
  51903. * @ignore (for internal use only)
  51904. */
  51905. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51906. if (offsetX === 0)
  51907. offsetX = this._epsilon;
  51908. else if (offsetX === 1)
  51909. offsetX = 1 - this._epsilon;
  51910. if (offsetY === 0)
  51911. offsetY = this._epsilon;
  51912. else if (offsetY === 1)
  51913. offsetY = 1 - this._epsilon;
  51914. var offset = index * this._vertexBufferSize;
  51915. this._vertexData[offset] = particle.position.x;
  51916. this._vertexData[offset + 1] = particle.position.y;
  51917. this._vertexData[offset + 2] = particle.position.z;
  51918. this._vertexData[offset + 3] = particle.color.r;
  51919. this._vertexData[offset + 4] = particle.color.g;
  51920. this._vertexData[offset + 5] = particle.color.b;
  51921. this._vertexData[offset + 6] = particle.color.a;
  51922. this._vertexData[offset + 7] = particle.angle;
  51923. this._vertexData[offset + 8] = particle.size;
  51924. this._vertexData[offset + 9] = offsetX;
  51925. this._vertexData[offset + 10] = offsetY;
  51926. this._vertexData[offset + 11] = particle.cellIndex;
  51927. };
  51928. ParticleSystem.prototype._stopSubEmitters = function () {
  51929. if (!this.activeSubSystems) {
  51930. return;
  51931. }
  51932. this.activeSubSystems.forEach(function (subSystem) {
  51933. subSystem.stop(true);
  51934. });
  51935. this.activeSubSystems = new Array();
  51936. };
  51937. ParticleSystem.prototype._removeFromRoot = function () {
  51938. if (!this._rootParticleSystem) {
  51939. return;
  51940. }
  51941. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51942. if (index !== -1) {
  51943. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51944. }
  51945. };
  51946. // end of sub system methods
  51947. ParticleSystem.prototype._update = function (newParticles) {
  51948. // Update current
  51949. this._alive = this._particles.length > 0;
  51950. this.updateFunction(this._particles);
  51951. // Add new ones
  51952. var worldMatrix;
  51953. if (this.emitter.position) {
  51954. var emitterMesh = this.emitter;
  51955. worldMatrix = emitterMesh.getWorldMatrix();
  51956. }
  51957. else {
  51958. var emitterPosition = this.emitter;
  51959. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51960. }
  51961. var particle;
  51962. for (var index = 0; index < newParticles; index++) {
  51963. if (this._particles.length === this._capacity) {
  51964. break;
  51965. }
  51966. particle = this._createParticle();
  51967. this._particles.push(particle);
  51968. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51969. if (this.startPositionFunction) {
  51970. this.startPositionFunction(worldMatrix, particle.position, particle);
  51971. }
  51972. else {
  51973. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51974. }
  51975. if (this.startDirectionFunction) {
  51976. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51977. }
  51978. else {
  51979. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51980. }
  51981. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51982. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51983. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51984. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51985. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51986. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51987. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51988. }
  51989. };
  51990. ParticleSystem.prototype._getEffect = function () {
  51991. if (this._customEffect) {
  51992. return this._customEffect;
  51993. }
  51994. ;
  51995. var defines = [];
  51996. if (this._scene.clipPlane) {
  51997. defines.push("#define CLIPPLANE");
  51998. }
  51999. if (this._isAnimationSheetEnabled) {
  52000. defines.push("#define ANIMATESHEET");
  52001. }
  52002. // Effect
  52003. var join = defines.join("\n");
  52004. if (this._cachedDefines !== join) {
  52005. this._cachedDefines = join;
  52006. var attributesNamesOrOptions;
  52007. var effectCreationOption;
  52008. if (this._isAnimationSheetEnabled) {
  52009. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52010. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52011. }
  52012. else {
  52013. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52014. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52015. }
  52016. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52017. }
  52018. return this._effect;
  52019. };
  52020. /**
  52021. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52022. */
  52023. ParticleSystem.prototype.animate = function () {
  52024. if (!this._started)
  52025. return;
  52026. var effect = this._getEffect();
  52027. // Check
  52028. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52029. return;
  52030. if (this._currentRenderId === this._scene.getRenderId()) {
  52031. return;
  52032. }
  52033. this._currentRenderId = this._scene.getRenderId();
  52034. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52035. // determine the number of particles we need to create
  52036. var newParticles;
  52037. if (this.manualEmitCount > -1) {
  52038. newParticles = this.manualEmitCount;
  52039. this._newPartsExcess = 0;
  52040. this.manualEmitCount = 0;
  52041. }
  52042. else {
  52043. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52044. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52045. }
  52046. if (this._newPartsExcess > 1.0) {
  52047. newParticles += this._newPartsExcess >> 0;
  52048. this._newPartsExcess -= this._newPartsExcess >> 0;
  52049. }
  52050. this._alive = false;
  52051. if (!this._stopped) {
  52052. this._actualFrame += this._scaledUpdateSpeed;
  52053. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52054. this.stop();
  52055. }
  52056. else {
  52057. newParticles = 0;
  52058. }
  52059. this._update(newParticles);
  52060. // Stopped?
  52061. if (this._stopped) {
  52062. if (!this._alive) {
  52063. this._started = false;
  52064. if (this.onAnimationEnd) {
  52065. this.onAnimationEnd();
  52066. }
  52067. if (this.disposeOnStop) {
  52068. this._scene._toBeDisposed.push(this);
  52069. }
  52070. }
  52071. }
  52072. // Animation sheet
  52073. if (this._isAnimationSheetEnabled) {
  52074. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52075. }
  52076. else {
  52077. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52078. }
  52079. // Update VBO
  52080. var offset = 0;
  52081. for (var index = 0; index < this._particles.length; index++) {
  52082. var particle = this._particles[index];
  52083. this._appendParticleVertexes(offset, particle);
  52084. offset += 4;
  52085. }
  52086. if (this._vertexBuffer) {
  52087. this._vertexBuffer.update(this._vertexData);
  52088. }
  52089. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52090. this.stop();
  52091. }
  52092. };
  52093. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52094. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52095. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52096. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52097. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52098. };
  52099. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52100. this._appendParticleVertex(offset++, particle, 0, 0);
  52101. this._appendParticleVertex(offset++, particle, 1, 0);
  52102. this._appendParticleVertex(offset++, particle, 1, 1);
  52103. this._appendParticleVertex(offset++, particle, 0, 1);
  52104. };
  52105. /**
  52106. * Rebuilds the particle system.
  52107. */
  52108. ParticleSystem.prototype.rebuild = function () {
  52109. this._createIndexBuffer();
  52110. if (this._vertexBuffer) {
  52111. this._vertexBuffer._rebuild();
  52112. }
  52113. };
  52114. /**
  52115. * Is this system ready to be used/rendered
  52116. * @return true if the system is ready
  52117. */
  52118. ParticleSystem.prototype.isReady = function () {
  52119. var effect = this._getEffect();
  52120. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52121. return false;
  52122. }
  52123. return true;
  52124. };
  52125. /**
  52126. * Renders the particle system in its current state.
  52127. * @returns the current number of particles
  52128. */
  52129. ParticleSystem.prototype.render = function () {
  52130. var effect = this._getEffect();
  52131. // Check
  52132. if (!this.isReady() || !this._particles.length) {
  52133. return 0;
  52134. }
  52135. var engine = this._scene.getEngine();
  52136. // Render
  52137. engine.enableEffect(effect);
  52138. engine.setState(false);
  52139. var viewMatrix = this._scene.getViewMatrix();
  52140. effect.setTexture("diffuseSampler", this.particleTexture);
  52141. effect.setMatrix("view", viewMatrix);
  52142. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52143. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52144. var baseSize = this.particleTexture.getBaseSize();
  52145. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52146. }
  52147. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52148. if (this._scene.clipPlane) {
  52149. var clipPlane = this._scene.clipPlane;
  52150. var invView = viewMatrix.clone();
  52151. invView.invert();
  52152. effect.setMatrix("invView", invView);
  52153. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52154. }
  52155. // VBOs
  52156. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52157. // Draw order
  52158. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52159. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52160. }
  52161. else {
  52162. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52163. }
  52164. if (this.forceDepthWrite) {
  52165. engine.setDepthWrite(true);
  52166. }
  52167. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52168. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52169. return this._particles.length;
  52170. };
  52171. /**
  52172. * Disposes the particle system and free the associated resources
  52173. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52174. */
  52175. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52176. if (disposeTexture === void 0) { disposeTexture = true; }
  52177. if (this._vertexBuffer) {
  52178. this._vertexBuffer.dispose();
  52179. this._vertexBuffer = null;
  52180. }
  52181. if (this._indexBuffer) {
  52182. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52183. this._indexBuffer = null;
  52184. }
  52185. if (disposeTexture && this.particleTexture) {
  52186. this.particleTexture.dispose();
  52187. this.particleTexture = null;
  52188. }
  52189. this._removeFromRoot();
  52190. // Remove from scene
  52191. var index = this._scene.particleSystems.indexOf(this);
  52192. if (index > -1) {
  52193. this._scene.particleSystems.splice(index, 1);
  52194. }
  52195. // Callback
  52196. this.onDisposeObservable.notifyObservers(this);
  52197. this.onDisposeObservable.clear();
  52198. };
  52199. /**
  52200. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52201. * @param radius The radius of the sphere to emit from
  52202. * @returns the emitter
  52203. */
  52204. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52205. if (radius === void 0) { radius = 1; }
  52206. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52207. this.particleEmitterType = particleEmitter;
  52208. return particleEmitter;
  52209. };
  52210. /**
  52211. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52212. * @param radius The radius of the sphere to emit from
  52213. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52214. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52215. * @returns the emitter
  52216. */
  52217. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52218. if (radius === void 0) { radius = 1; }
  52219. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52220. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52221. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52222. this.particleEmitterType = particleEmitter;
  52223. return particleEmitter;
  52224. };
  52225. /**
  52226. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52227. * @param radius The radius of the cone to emit from
  52228. * @param angle The base angle of the cone
  52229. * @returns the emitter
  52230. */
  52231. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52232. if (radius === void 0) { radius = 1; }
  52233. if (angle === void 0) { angle = Math.PI / 4; }
  52234. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52235. this.particleEmitterType = particleEmitter;
  52236. return particleEmitter;
  52237. };
  52238. // 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.
  52239. /**
  52240. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52241. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52242. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52243. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52244. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52245. * @returns the emitter
  52246. */
  52247. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52248. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52249. this.particleEmitterType = particleEmitter;
  52250. this.direction1 = direction1;
  52251. this.direction2 = direction2;
  52252. this.minEmitBox = minEmitBox;
  52253. this.maxEmitBox = maxEmitBox;
  52254. return particleEmitter;
  52255. };
  52256. // Clone
  52257. /**
  52258. * Clones the particle system.
  52259. * @param name The name of the cloned object
  52260. * @param newEmitter The new emitter to use
  52261. * @returns the cloned particle system
  52262. */
  52263. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52264. var custom = null;
  52265. var program = null;
  52266. if (this.customShader != null) {
  52267. program = this.customShader;
  52268. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52269. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52270. }
  52271. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52272. result.customShader = program;
  52273. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52274. if (newEmitter === undefined) {
  52275. newEmitter = this.emitter;
  52276. }
  52277. result.emitter = newEmitter;
  52278. if (this.particleTexture) {
  52279. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52280. }
  52281. if (!this.preventAutoStart) {
  52282. result.start();
  52283. }
  52284. return result;
  52285. };
  52286. /**
  52287. * Serializes the particle system to a JSON object.
  52288. * @returns the JSON object
  52289. */
  52290. ParticleSystem.prototype.serialize = function () {
  52291. var serializationObject = {};
  52292. serializationObject.name = this.name;
  52293. serializationObject.id = this.id;
  52294. // Emitter
  52295. if (this.emitter.position) {
  52296. var emitterMesh = this.emitter;
  52297. serializationObject.emitterId = emitterMesh.id;
  52298. }
  52299. else {
  52300. var emitterPosition = this.emitter;
  52301. serializationObject.emitter = emitterPosition.asArray();
  52302. }
  52303. serializationObject.capacity = this.getCapacity();
  52304. if (this.particleTexture) {
  52305. serializationObject.textureName = this.particleTexture.name;
  52306. }
  52307. // Animations
  52308. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52309. // Particle system
  52310. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52311. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52312. serializationObject.minSize = this.minSize;
  52313. serializationObject.maxSize = this.maxSize;
  52314. serializationObject.minEmitPower = this.minEmitPower;
  52315. serializationObject.maxEmitPower = this.maxEmitPower;
  52316. serializationObject.minLifeTime = this.minLifeTime;
  52317. serializationObject.maxLifeTime = this.maxLifeTime;
  52318. serializationObject.emitRate = this.emitRate;
  52319. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52320. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52321. serializationObject.gravity = this.gravity.asArray();
  52322. serializationObject.direction1 = this.direction1.asArray();
  52323. serializationObject.direction2 = this.direction2.asArray();
  52324. serializationObject.color1 = this.color1.asArray();
  52325. serializationObject.color2 = this.color2.asArray();
  52326. serializationObject.colorDead = this.colorDead.asArray();
  52327. serializationObject.updateSpeed = this.updateSpeed;
  52328. serializationObject.targetStopDuration = this.targetStopDuration;
  52329. serializationObject.textureMask = this.textureMask.asArray();
  52330. serializationObject.blendMode = this.blendMode;
  52331. serializationObject.customShader = this.customShader;
  52332. serializationObject.preventAutoStart = this.preventAutoStart;
  52333. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52334. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52335. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52336. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52337. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52338. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52339. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52340. // Emitter
  52341. if (this.particleEmitterType) {
  52342. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52343. }
  52344. return serializationObject;
  52345. };
  52346. /**
  52347. * Parses a JSON object to create a particle system.
  52348. * @param parsedParticleSystem The JSON object to parse
  52349. * @param scene The scene to create the particle system in
  52350. * @param rootUrl The root url to use to load external dependencies like texture
  52351. * @returns the Parsed particle system
  52352. */
  52353. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52354. var name = parsedParticleSystem.name;
  52355. var custom = null;
  52356. var program = null;
  52357. if (parsedParticleSystem.customShader) {
  52358. program = parsedParticleSystem.customShader;
  52359. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52360. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52361. }
  52362. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52363. particleSystem.customShader = program;
  52364. if (parsedParticleSystem.id) {
  52365. particleSystem.id = parsedParticleSystem.id;
  52366. }
  52367. // Auto start
  52368. if (parsedParticleSystem.preventAutoStart) {
  52369. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52370. }
  52371. // Texture
  52372. if (parsedParticleSystem.textureName) {
  52373. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52374. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52375. }
  52376. // Emitter
  52377. if (parsedParticleSystem.emitterId) {
  52378. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52379. }
  52380. else {
  52381. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52382. }
  52383. // Animations
  52384. if (parsedParticleSystem.animations) {
  52385. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52386. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52387. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52388. }
  52389. }
  52390. if (parsedParticleSystem.autoAnimate) {
  52391. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52392. }
  52393. // Particle system
  52394. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52395. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52396. particleSystem.minSize = parsedParticleSystem.minSize;
  52397. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52398. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52399. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52400. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52401. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52402. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52403. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52404. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52405. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52406. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52407. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52408. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52409. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52410. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52411. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52412. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52413. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52414. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52415. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52416. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52417. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52418. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52419. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52420. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52421. if (!particleSystem.preventAutoStart) {
  52422. particleSystem.start();
  52423. }
  52424. return particleSystem;
  52425. };
  52426. /**
  52427. * Source color is added to the destination color without alpha affecting the result.
  52428. */
  52429. ParticleSystem.BLENDMODE_ONEONE = 0;
  52430. /**
  52431. * Blend current color and particle color using particle’s alpha.
  52432. */
  52433. ParticleSystem.BLENDMODE_STANDARD = 1;
  52434. return ParticleSystem;
  52435. }());
  52436. BABYLON.ParticleSystem = ParticleSystem;
  52437. })(BABYLON || (BABYLON = {}));
  52438. //# sourceMappingURL=babylon.particleSystem.js.map
  52439. "use strict";
  52440. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52441. "use strict";
  52442. var BABYLON;
  52443. (function (BABYLON) {
  52444. /**
  52445. * Particle emitter emitting particles from the inside of a box.
  52446. * It emits the particles randomly between 2 given directions.
  52447. */
  52448. var BoxParticleEmitter = /** @class */ (function () {
  52449. /**
  52450. * Creates a new instance of @see BoxParticleEmitter
  52451. */
  52452. function BoxParticleEmitter() {
  52453. /**
  52454. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52455. */
  52456. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52457. /**
  52458. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52459. */
  52460. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52461. /**
  52462. * 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.
  52463. */
  52464. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52465. /**
  52466. * 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.
  52467. */
  52468. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52469. }
  52470. /**
  52471. * Called by the particle System when the direction is computed for the created particle.
  52472. * @param emitPower is the power of the particle (speed)
  52473. * @param worldMatrix is the world matrix of the particle system
  52474. * @param directionToUpdate is the direction vector to update with the result
  52475. * @param particle is the particle we are computed the direction for
  52476. */
  52477. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52478. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52479. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52480. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52481. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52482. };
  52483. /**
  52484. * Called by the particle System when the position is computed for the created particle.
  52485. * @param worldMatrix is the world matrix of the particle system
  52486. * @param positionToUpdate is the position vector to update with the result
  52487. * @param particle is the particle we are computed the position for
  52488. */
  52489. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52490. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52491. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52492. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52493. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52494. };
  52495. /**
  52496. * Clones the current emitter and returns a copy of it
  52497. * @returns the new emitter
  52498. */
  52499. BoxParticleEmitter.prototype.clone = function () {
  52500. var newOne = new BoxParticleEmitter();
  52501. BABYLON.Tools.DeepCopy(this, newOne);
  52502. return newOne;
  52503. };
  52504. /**
  52505. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52506. * @param effect defines the update shader
  52507. */
  52508. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52509. effect.setVector3("direction1", this.direction1);
  52510. effect.setVector3("direction2", this.direction2);
  52511. effect.setVector3("minEmitBox", this.minEmitBox);
  52512. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52513. };
  52514. /**
  52515. * Returns a string to use to update the GPU particles update shader
  52516. * @returns a string containng the defines string
  52517. */
  52518. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52519. return "#define BOXEMITTER";
  52520. };
  52521. /**
  52522. * Returns the string "BoxEmitter"
  52523. * @returns a string containing the class name
  52524. */
  52525. BoxParticleEmitter.prototype.getClassName = function () {
  52526. return "BoxEmitter";
  52527. };
  52528. /**
  52529. * Serializes the particle system to a JSON object.
  52530. * @returns the JSON object
  52531. */
  52532. BoxParticleEmitter.prototype.serialize = function () {
  52533. var serializationObject = {};
  52534. serializationObject.type = this.getClassName();
  52535. serializationObject.direction1 = this.direction1.asArray();
  52536. ;
  52537. serializationObject.direction2 = this.direction2.asArray();
  52538. ;
  52539. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52540. ;
  52541. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52542. ;
  52543. return serializationObject;
  52544. };
  52545. /**
  52546. * Parse properties from a JSON object
  52547. * @param serializationObject defines the JSON object
  52548. */
  52549. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52550. this.direction1.copyFrom(serializationObject.direction1);
  52551. this.direction2.copyFrom(serializationObject.direction2);
  52552. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52553. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52554. };
  52555. return BoxParticleEmitter;
  52556. }());
  52557. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52558. })(BABYLON || (BABYLON = {}));
  52559. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52560. "use strict";
  52561. var BABYLON;
  52562. (function (BABYLON) {
  52563. /**
  52564. * Particle emitter emitting particles from the inside of a cone.
  52565. * It emits the particles alongside the cone volume from the base to the particle.
  52566. * The emission direction might be randomized.
  52567. */
  52568. var ConeParticleEmitter = /** @class */ (function () {
  52569. /**
  52570. * Creates a new instance of @see ConeParticleEmitter
  52571. * @param radius the radius of the emission cone (1 by default)
  52572. * @param angles the cone base angle (PI by default)
  52573. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52574. */
  52575. function ConeParticleEmitter(radius,
  52576. /**
  52577. * The radius of the emission cone.
  52578. */
  52579. angle,
  52580. /**
  52581. * The cone base angle.
  52582. */
  52583. directionRandomizer) {
  52584. if (radius === void 0) { radius = 1; }
  52585. if (angle === void 0) { angle = Math.PI; }
  52586. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52587. this.angle = angle;
  52588. this.directionRandomizer = directionRandomizer;
  52589. this.radius = radius;
  52590. }
  52591. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52592. /**
  52593. * Gets the radius of the emission cone.
  52594. */
  52595. get: function () {
  52596. return this._radius;
  52597. },
  52598. /**
  52599. * Sets the radius of the emission cone.
  52600. */
  52601. set: function (value) {
  52602. this._radius = value;
  52603. if (this.angle !== 0) {
  52604. this._height = value / Math.tan(this.angle / 2);
  52605. }
  52606. else {
  52607. this._height = 1;
  52608. }
  52609. },
  52610. enumerable: true,
  52611. configurable: true
  52612. });
  52613. /**
  52614. * Called by the particle System when the direction is computed for the created particle.
  52615. * @param emitPower is the power of the particle (speed)
  52616. * @param worldMatrix is the world matrix of the particle system
  52617. * @param directionToUpdate is the direction vector to update with the result
  52618. * @param particle is the particle we are computed the direction for
  52619. */
  52620. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52621. if (this.angle === 0) {
  52622. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52623. }
  52624. else {
  52625. // measure the direction Vector from the emitter to the particle.
  52626. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52627. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52628. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52629. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52630. direction.x += randX;
  52631. direction.y += randY;
  52632. direction.z += randZ;
  52633. direction.normalize();
  52634. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52635. }
  52636. };
  52637. /**
  52638. * Called by the particle System when the position is computed for the created particle.
  52639. * @param worldMatrix is the world matrix of the particle system
  52640. * @param positionToUpdate is the position vector to update with the result
  52641. * @param particle is the particle we are computed the position for
  52642. */
  52643. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52644. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52645. var h = BABYLON.Scalar.RandomRange(0, 1);
  52646. // Better distribution in a cone at normal angles.
  52647. h = 1 - h * h;
  52648. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52649. radius = radius * h;
  52650. var randX = radius * Math.sin(s);
  52651. var randZ = radius * Math.cos(s);
  52652. var randY = h * this._height;
  52653. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52654. };
  52655. /**
  52656. * Clones the current emitter and returns a copy of it
  52657. * @returns the new emitter
  52658. */
  52659. ConeParticleEmitter.prototype.clone = function () {
  52660. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52661. BABYLON.Tools.DeepCopy(this, newOne);
  52662. return newOne;
  52663. };
  52664. /**
  52665. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52666. * @param effect defines the update shader
  52667. */
  52668. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52669. effect.setFloat("radius", this.radius);
  52670. effect.setFloat("angle", this.angle);
  52671. effect.setFloat("height", this._height);
  52672. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52673. };
  52674. /**
  52675. * Returns a string to use to update the GPU particles update shader
  52676. * @returns a string containng the defines string
  52677. */
  52678. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52679. return "#define CONEEMITTER";
  52680. };
  52681. /**
  52682. * Returns the string "BoxEmitter"
  52683. * @returns a string containing the class name
  52684. */
  52685. ConeParticleEmitter.prototype.getClassName = function () {
  52686. return "ConeEmitter";
  52687. };
  52688. /**
  52689. * Serializes the particle system to a JSON object.
  52690. * @returns the JSON object
  52691. */
  52692. ConeParticleEmitter.prototype.serialize = function () {
  52693. var serializationObject = {};
  52694. serializationObject.type = this.getClassName();
  52695. serializationObject.radius = this.radius;
  52696. serializationObject.angle = this.angle;
  52697. serializationObject.directionRandomizer = this.directionRandomizer;
  52698. return serializationObject;
  52699. };
  52700. /**
  52701. * Parse properties from a JSON object
  52702. * @param serializationObject defines the JSON object
  52703. */
  52704. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52705. this.radius = serializationObject.radius;
  52706. this.angle = serializationObject.angle;
  52707. this.directionRandomizer = serializationObject.directionRandomizer;
  52708. };
  52709. return ConeParticleEmitter;
  52710. }());
  52711. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52712. })(BABYLON || (BABYLON = {}));
  52713. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52714. "use strict";
  52715. var BABYLON;
  52716. (function (BABYLON) {
  52717. /**
  52718. * Particle emitter emitting particles from the inside of a sphere.
  52719. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52720. */
  52721. var SphereParticleEmitter = /** @class */ (function () {
  52722. /**
  52723. * Creates a new instance of @see SphereParticleEmitter
  52724. * @param radius the radius of the emission sphere (1 by default)
  52725. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52726. */
  52727. function SphereParticleEmitter(
  52728. /**
  52729. * The radius of the emission sphere.
  52730. */
  52731. radius,
  52732. /**
  52733. * How much to randomize the particle direction [0-1].
  52734. */
  52735. directionRandomizer) {
  52736. if (radius === void 0) { radius = 1; }
  52737. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52738. this.radius = radius;
  52739. this.directionRandomizer = directionRandomizer;
  52740. }
  52741. /**
  52742. * Called by the particle System when the direction is computed for the created particle.
  52743. * @param emitPower is the power of the particle (speed)
  52744. * @param worldMatrix is the world matrix of the particle system
  52745. * @param directionToUpdate is the direction vector to update with the result
  52746. * @param particle is the particle we are computed the direction for
  52747. */
  52748. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52749. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52750. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52751. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52752. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52753. direction.x += randX;
  52754. direction.y += randY;
  52755. direction.z += randZ;
  52756. direction.normalize();
  52757. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52758. };
  52759. /**
  52760. * Called by the particle System when the position is computed for the created particle.
  52761. * @param worldMatrix is the world matrix of the particle system
  52762. * @param positionToUpdate is the position vector to update with the result
  52763. * @param particle is the particle we are computed the position for
  52764. */
  52765. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52766. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52767. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52768. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52769. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52770. var randY = randRadius * Math.cos(theta);
  52771. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52772. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52773. };
  52774. /**
  52775. * Clones the current emitter and returns a copy of it
  52776. * @returns the new emitter
  52777. */
  52778. SphereParticleEmitter.prototype.clone = function () {
  52779. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52780. BABYLON.Tools.DeepCopy(this, newOne);
  52781. return newOne;
  52782. };
  52783. /**
  52784. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52785. * @param effect defines the update shader
  52786. */
  52787. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52788. effect.setFloat("radius", this.radius);
  52789. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52790. };
  52791. /**
  52792. * Returns a string to use to update the GPU particles update shader
  52793. * @returns a string containng the defines string
  52794. */
  52795. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52796. return "#define SPHEREEMITTER";
  52797. };
  52798. /**
  52799. * Returns the string "SphereParticleEmitter"
  52800. * @returns a string containing the class name
  52801. */
  52802. SphereParticleEmitter.prototype.getClassName = function () {
  52803. return "SphereParticleEmitter";
  52804. };
  52805. /**
  52806. * Serializes the particle system to a JSON object.
  52807. * @returns the JSON object
  52808. */
  52809. SphereParticleEmitter.prototype.serialize = function () {
  52810. var serializationObject = {};
  52811. serializationObject.type = this.getClassName();
  52812. serializationObject.radius = this.radius;
  52813. serializationObject.directionRandomizer = this.directionRandomizer;
  52814. return serializationObject;
  52815. };
  52816. /**
  52817. * Parse properties from a JSON object
  52818. * @param serializationObject defines the JSON object
  52819. */
  52820. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52821. this.radius = serializationObject.radius;
  52822. this.directionRandomizer = serializationObject.directionRandomizer;
  52823. };
  52824. return SphereParticleEmitter;
  52825. }());
  52826. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52827. /**
  52828. * Particle emitter emitting particles from the inside of a sphere.
  52829. * It emits the particles randomly between two vectors.
  52830. */
  52831. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52832. __extends(SphereDirectedParticleEmitter, _super);
  52833. /**
  52834. * Creates a new instance of @see SphereDirectedParticleEmitter
  52835. * @param radius the radius of the emission sphere (1 by default)
  52836. * @param direction1 the min limit of the emission direction (up vector by default)
  52837. * @param direction2 the max limit of the emission direction (up vector by default)
  52838. */
  52839. function SphereDirectedParticleEmitter(radius,
  52840. /**
  52841. * The min limit of the emission direction.
  52842. */
  52843. direction1,
  52844. /**
  52845. * The max limit of the emission direction.
  52846. */
  52847. direction2) {
  52848. if (radius === void 0) { radius = 1; }
  52849. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52850. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52851. var _this = _super.call(this, radius) || this;
  52852. _this.direction1 = direction1;
  52853. _this.direction2 = direction2;
  52854. return _this;
  52855. }
  52856. /**
  52857. * Called by the particle System when the direction is computed for the created particle.
  52858. * @param emitPower is the power of the particle (speed)
  52859. * @param worldMatrix is the world matrix of the particle system
  52860. * @param directionToUpdate is the direction vector to update with the result
  52861. * @param particle is the particle we are computed the direction for
  52862. */
  52863. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52864. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52865. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52866. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52867. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52868. };
  52869. /**
  52870. * Clones the current emitter and returns a copy of it
  52871. * @returns the new emitter
  52872. */
  52873. SphereDirectedParticleEmitter.prototype.clone = function () {
  52874. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52875. BABYLON.Tools.DeepCopy(this, newOne);
  52876. return newOne;
  52877. };
  52878. /**
  52879. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52880. * @param effect defines the update shader
  52881. */
  52882. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52883. effect.setFloat("radius", this.radius);
  52884. effect.setVector3("direction1", this.direction1);
  52885. effect.setVector3("direction2", this.direction2);
  52886. };
  52887. /**
  52888. * Returns a string to use to update the GPU particles update shader
  52889. * @returns a string containng the defines string
  52890. */
  52891. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52892. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52893. };
  52894. /**
  52895. * Returns the string "SphereDirectedParticleEmitter"
  52896. * @returns a string containing the class name
  52897. */
  52898. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52899. return "SphereDirectedParticleEmitter";
  52900. };
  52901. /**
  52902. * Serializes the particle system to a JSON object.
  52903. * @returns the JSON object
  52904. */
  52905. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52906. var serializationObject = _super.prototype.serialize.call(this);
  52907. ;
  52908. serializationObject.direction1 = this.direction1.asArray();
  52909. ;
  52910. serializationObject.direction2 = this.direction2.asArray();
  52911. ;
  52912. return serializationObject;
  52913. };
  52914. /**
  52915. * Parse properties from a JSON object
  52916. * @param serializationObject defines the JSON object
  52917. */
  52918. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52919. _super.prototype.parse.call(this, serializationObject);
  52920. this.direction1.copyFrom(serializationObject.direction1);
  52921. this.direction2.copyFrom(serializationObject.direction2);
  52922. };
  52923. return SphereDirectedParticleEmitter;
  52924. }(SphereParticleEmitter));
  52925. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52926. })(BABYLON || (BABYLON = {}));
  52927. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52928. "use strict";
  52929. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52930. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52931. s = arguments[i];
  52932. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52933. t[p] = s[p];
  52934. }
  52935. return t;
  52936. };
  52937. var BABYLON;
  52938. (function (BABYLON) {
  52939. /**
  52940. * This represents a GPU particle system in Babylon
  52941. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52942. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52943. */
  52944. var GPUParticleSystem = /** @class */ (function () {
  52945. /**
  52946. * Instantiates a GPU particle system.
  52947. * 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.
  52948. * @param name The name of the particle system
  52949. * @param capacity The max number of particles alive at the same time
  52950. * @param scene The scene the particle system belongs to
  52951. */
  52952. function GPUParticleSystem(name, options, scene) {
  52953. /**
  52954. * The emitter represents the Mesh or position we are attaching the particle system to.
  52955. */
  52956. this.emitter = null;
  52957. /**
  52958. * The rendering group used by the Particle system to chose when to render.
  52959. */
  52960. this.renderingGroupId = 0;
  52961. /**
  52962. * The layer mask we are rendering the particles through.
  52963. */
  52964. this.layerMask = 0x0FFFFFFF;
  52965. this._targetIndex = 0;
  52966. this._currentRenderId = -1;
  52967. this._started = false;
  52968. this._stopped = false;
  52969. this._timeDelta = 0;
  52970. this._attributesStrideSize = 14;
  52971. this._actualFrame = 0;
  52972. /**
  52973. * List of animations used by the particle system.
  52974. */
  52975. this.animations = [];
  52976. /**
  52977. * An event triggered when the system is disposed.
  52978. */
  52979. this.onDisposeObservable = new BABYLON.Observable();
  52980. /**
  52981. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52982. */
  52983. this.updateSpeed = 0.01;
  52984. /**
  52985. * The amount of time the particle system is running (depends of the overall update speed).
  52986. */
  52987. this.targetStopDuration = 0;
  52988. /**
  52989. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52990. */
  52991. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52992. /**
  52993. * Minimum life time of emitting particles.
  52994. */
  52995. this.minLifeTime = 1;
  52996. /**
  52997. * Maximum life time of emitting particles.
  52998. */
  52999. this.maxLifeTime = 1;
  53000. /**
  53001. * Minimum Size of emitting particles.
  53002. */
  53003. this.minSize = 1;
  53004. /**
  53005. * Maximum Size of emitting particles.
  53006. */
  53007. this.maxSize = 1;
  53008. /**
  53009. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53010. */
  53011. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53012. /**
  53013. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53014. */
  53015. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53016. /**
  53017. * Color the particle will have at the end of its lifetime.
  53018. */
  53019. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53020. /**
  53021. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53022. */
  53023. this.emitRate = 100;
  53024. /**
  53025. * You can use gravity if you want to give an orientation to your particles.
  53026. */
  53027. this.gravity = BABYLON.Vector3.Zero();
  53028. /**
  53029. * Minimum power of emitting particles.
  53030. */
  53031. this.minEmitPower = 1;
  53032. /**
  53033. * Maximum power of emitting particles.
  53034. */
  53035. this.maxEmitPower = 1;
  53036. /**
  53037. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53038. * to override the particles.
  53039. */
  53040. this.forceDepthWrite = false;
  53041. this.id = name;
  53042. this.name = name;
  53043. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53044. this._engine = this._scene.getEngine();
  53045. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53046. this._capacity = fullOptions.capacity;
  53047. this._activeCount = fullOptions.capacity;
  53048. this._currentActiveCount = 0;
  53049. this._scene.particleSystems.push(this);
  53050. this._updateEffectOptions = {
  53051. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53052. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53053. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53054. uniformBuffersNames: [],
  53055. samplers: ["randomSampler"],
  53056. defines: "",
  53057. fallbacks: null,
  53058. onCompiled: null,
  53059. onError: null,
  53060. indexParameters: null,
  53061. maxSimultaneousLights: 0,
  53062. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53063. };
  53064. // Random data
  53065. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53066. var d = [];
  53067. for (var i = 0; i < maxTextureSize; ++i) {
  53068. d.push(Math.random());
  53069. d.push(Math.random());
  53070. d.push(Math.random());
  53071. d.push(Math.random());
  53072. }
  53073. 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);
  53074. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53075. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53076. this._randomTextureSize = maxTextureSize;
  53077. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53078. }
  53079. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53080. /**
  53081. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53082. */
  53083. get: function () {
  53084. if (!BABYLON.Engine.LastCreatedEngine) {
  53085. return false;
  53086. }
  53087. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53088. },
  53089. enumerable: true,
  53090. configurable: true
  53091. });
  53092. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53093. /**
  53094. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53095. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53096. */
  53097. get: function () {
  53098. if (this.particleEmitterType.direction1) {
  53099. return this.particleEmitterType.direction1;
  53100. }
  53101. return BABYLON.Vector3.Zero();
  53102. },
  53103. set: function (value) {
  53104. if (this.particleEmitterType.direction1) {
  53105. this.particleEmitterType.direction1 = value;
  53106. }
  53107. },
  53108. enumerable: true,
  53109. configurable: true
  53110. });
  53111. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53112. /**
  53113. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53114. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53115. */
  53116. get: function () {
  53117. if (this.particleEmitterType.direction2) {
  53118. return this.particleEmitterType.direction2;
  53119. }
  53120. return BABYLON.Vector3.Zero();
  53121. },
  53122. set: function (value) {
  53123. if (this.particleEmitterType.direction2) {
  53124. this.particleEmitterType.direction2 = value;
  53125. }
  53126. },
  53127. enumerable: true,
  53128. configurable: true
  53129. });
  53130. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53131. /**
  53132. * 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.
  53133. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53134. */
  53135. get: function () {
  53136. if (this.particleEmitterType.minEmitBox) {
  53137. return this.particleEmitterType.minEmitBox;
  53138. }
  53139. return BABYLON.Vector3.Zero();
  53140. },
  53141. set: function (value) {
  53142. if (this.particleEmitterType.minEmitBox) {
  53143. this.particleEmitterType.minEmitBox = value;
  53144. }
  53145. },
  53146. enumerable: true,
  53147. configurable: true
  53148. });
  53149. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53150. /**
  53151. * 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.
  53152. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53153. */
  53154. get: function () {
  53155. if (this.particleEmitterType.maxEmitBox) {
  53156. return this.particleEmitterType.maxEmitBox;
  53157. }
  53158. return BABYLON.Vector3.Zero();
  53159. },
  53160. set: function (value) {
  53161. if (this.particleEmitterType.maxEmitBox) {
  53162. this.particleEmitterType.maxEmitBox = value;
  53163. }
  53164. },
  53165. enumerable: true,
  53166. configurable: true
  53167. });
  53168. /**
  53169. * Gets the maximum number of particles active at the same time.
  53170. * @returns The max number of active particles.
  53171. */
  53172. GPUParticleSystem.prototype.getCapacity = function () {
  53173. return this._capacity;
  53174. };
  53175. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53176. /**
  53177. * Gets or set the number of active particles
  53178. */
  53179. get: function () {
  53180. return this._activeCount;
  53181. },
  53182. set: function (value) {
  53183. this._activeCount = Math.min(value, this._capacity);
  53184. },
  53185. enumerable: true,
  53186. configurable: true
  53187. });
  53188. /**
  53189. * Is this system ready to be used/rendered
  53190. * @return true if the system is ready
  53191. */
  53192. GPUParticleSystem.prototype.isReady = function () {
  53193. if (!this._updateEffect) {
  53194. this._recreateUpdateEffect();
  53195. this._recreateRenderEffect();
  53196. return false;
  53197. }
  53198. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53199. return false;
  53200. }
  53201. return true;
  53202. };
  53203. /**
  53204. * Gets Wether the system has been started.
  53205. * @returns True if it has been started, otherwise false.
  53206. */
  53207. GPUParticleSystem.prototype.isStarted = function () {
  53208. return this._started;
  53209. };
  53210. /**
  53211. * Starts the particle system and begins to emit.
  53212. */
  53213. GPUParticleSystem.prototype.start = function () {
  53214. this._started = true;
  53215. this._stopped = false;
  53216. };
  53217. /**
  53218. * Stops the particle system.
  53219. */
  53220. GPUParticleSystem.prototype.stop = function () {
  53221. this._stopped = true;
  53222. };
  53223. /**
  53224. * Remove all active particles
  53225. */
  53226. GPUParticleSystem.prototype.reset = function () {
  53227. this._releaseBuffers();
  53228. this._releaseVAOs();
  53229. this._currentActiveCount = 0;
  53230. this._targetIndex = 0;
  53231. };
  53232. /**
  53233. * Returns the string "GPUParticleSystem"
  53234. * @returns a string containing the class name
  53235. */
  53236. GPUParticleSystem.prototype.getClassName = function () {
  53237. return "GPUParticleSystem";
  53238. };
  53239. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53240. var updateVertexBuffers = {};
  53241. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53242. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53243. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53244. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53245. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53246. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53247. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53248. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53249. this._engine.bindArrayBuffer(null);
  53250. return vao;
  53251. };
  53252. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53253. var renderVertexBuffers = {};
  53254. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53255. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53256. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53257. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53258. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53259. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53260. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53261. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53262. this._engine.bindArrayBuffer(null);
  53263. return vao;
  53264. };
  53265. GPUParticleSystem.prototype._initialize = function (force) {
  53266. if (force === void 0) { force = false; }
  53267. if (this._buffer0 && !force) {
  53268. return;
  53269. }
  53270. var engine = this._scene.getEngine();
  53271. var data = new Array();
  53272. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53273. // position
  53274. data.push(0.0);
  53275. data.push(0.0);
  53276. data.push(0.0);
  53277. // Age and life
  53278. data.push(0.0); // create the particle as a dead one to create a new one at start
  53279. data.push(0.0);
  53280. // Seed
  53281. data.push(Math.random());
  53282. // Size
  53283. data.push(0.0);
  53284. // color
  53285. data.push(0.0);
  53286. data.push(0.0);
  53287. data.push(0.0);
  53288. data.push(0.0);
  53289. // direction
  53290. data.push(0.0);
  53291. data.push(0.0);
  53292. data.push(0.0);
  53293. }
  53294. // Sprite data
  53295. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53296. -0.5, 0.5, 0, 1,
  53297. -0.5, -0.5, 0, 0,
  53298. 0.5, -0.5, 1, 0]);
  53299. // Buffers
  53300. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53301. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53302. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53303. // Update VAO
  53304. this._updateVAO = [];
  53305. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53306. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53307. // Render VAO
  53308. this._renderVAO = [];
  53309. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53310. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53311. // Links
  53312. this._sourceBuffer = this._buffer0;
  53313. this._targetBuffer = this._buffer1;
  53314. };
  53315. /** @ignore */
  53316. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53317. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53318. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53319. return;
  53320. }
  53321. this._updateEffectOptions.defines = defines;
  53322. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53323. };
  53324. /** @ignore */
  53325. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53326. var defines = "";
  53327. if (this._scene.clipPlane) {
  53328. defines = "\n#define CLIPPLANE";
  53329. }
  53330. if (this._renderEffect && this._renderEffect.defines === defines) {
  53331. return;
  53332. }
  53333. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53334. };
  53335. /**
  53336. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53337. */
  53338. GPUParticleSystem.prototype.animate = function () {
  53339. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53340. this._actualFrame += this._timeDelta;
  53341. if (!this._stopped) {
  53342. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53343. this.stop();
  53344. }
  53345. }
  53346. };
  53347. /**
  53348. * Renders the particle system in its current state.
  53349. * @returns the current number of particles
  53350. */
  53351. GPUParticleSystem.prototype.render = function () {
  53352. if (!this._started) {
  53353. return 0;
  53354. }
  53355. this._recreateUpdateEffect();
  53356. this._recreateRenderEffect();
  53357. if (!this.isReady()) {
  53358. return 0;
  53359. }
  53360. if (this._currentRenderId === this._scene.getRenderId()) {
  53361. return 0;
  53362. }
  53363. this._currentRenderId = this._scene.getRenderId();
  53364. // Get everything ready to render
  53365. this._initialize();
  53366. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53367. // Enable update effect
  53368. this._engine.enableEffect(this._updateEffect);
  53369. this._engine.setState(false);
  53370. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53371. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53372. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53373. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53374. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53375. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53376. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53377. this._updateEffect.setDirectColor4("color1", this.color1);
  53378. this._updateEffect.setDirectColor4("color2", this.color2);
  53379. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53380. this._updateEffect.setVector3("gravity", this.gravity);
  53381. if (this.particleEmitterType) {
  53382. this.particleEmitterType.applyToShader(this._updateEffect);
  53383. }
  53384. var emitterWM;
  53385. if (this.emitter.position) {
  53386. var emitterMesh = this.emitter;
  53387. emitterWM = emitterMesh.getWorldMatrix();
  53388. }
  53389. else {
  53390. var emitterPosition = this.emitter;
  53391. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53392. }
  53393. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53394. // Bind source VAO
  53395. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53396. // Update
  53397. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53398. this._engine.setRasterizerState(false);
  53399. this._engine.beginTransformFeedback();
  53400. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53401. this._engine.endTransformFeedback();
  53402. this._engine.setRasterizerState(true);
  53403. this._engine.bindTransformFeedbackBuffer(null);
  53404. // Enable render effect
  53405. this._engine.enableEffect(this._renderEffect);
  53406. var viewMatrix = this._scene.getViewMatrix();
  53407. this._renderEffect.setMatrix("view", viewMatrix);
  53408. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53409. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53410. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53411. if (this._scene.clipPlane) {
  53412. var clipPlane = this._scene.clipPlane;
  53413. var invView = viewMatrix.clone();
  53414. invView.invert();
  53415. this._renderEffect.setMatrix("invView", invView);
  53416. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53417. }
  53418. // Draw order
  53419. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53420. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53421. }
  53422. else {
  53423. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53424. }
  53425. if (this.forceDepthWrite) {
  53426. this._engine.setDepthWrite(true);
  53427. }
  53428. // Bind source VAO
  53429. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53430. // Render
  53431. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53432. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53433. // Switch VAOs
  53434. this._targetIndex++;
  53435. if (this._targetIndex === 2) {
  53436. this._targetIndex = 0;
  53437. }
  53438. // Switch buffers
  53439. var tmpBuffer = this._sourceBuffer;
  53440. this._sourceBuffer = this._targetBuffer;
  53441. this._targetBuffer = tmpBuffer;
  53442. return this._currentActiveCount;
  53443. };
  53444. /**
  53445. * Rebuilds the particle system
  53446. */
  53447. GPUParticleSystem.prototype.rebuild = function () {
  53448. this._initialize(true);
  53449. };
  53450. GPUParticleSystem.prototype._releaseBuffers = function () {
  53451. if (this._buffer0) {
  53452. this._buffer0.dispose();
  53453. this._buffer0 = null;
  53454. }
  53455. if (this._buffer1) {
  53456. this._buffer1.dispose();
  53457. this._buffer1 = null;
  53458. }
  53459. if (this._spriteBuffer) {
  53460. this._spriteBuffer.dispose();
  53461. this._spriteBuffer = null;
  53462. }
  53463. };
  53464. GPUParticleSystem.prototype._releaseVAOs = function () {
  53465. if (!this._updateVAO) {
  53466. return;
  53467. }
  53468. for (var index = 0; index < this._updateVAO.length; index++) {
  53469. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53470. }
  53471. this._updateVAO = [];
  53472. for (var index = 0; index < this._renderVAO.length; index++) {
  53473. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53474. }
  53475. this._renderVAO = [];
  53476. };
  53477. /**
  53478. * Disposes the particle system and free the associated resources
  53479. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53480. */
  53481. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53482. if (disposeTexture === void 0) { disposeTexture = true; }
  53483. var index = this._scene.particleSystems.indexOf(this);
  53484. if (index > -1) {
  53485. this._scene.particleSystems.splice(index, 1);
  53486. }
  53487. this._releaseBuffers();
  53488. this._releaseVAOs();
  53489. if (this._randomTexture) {
  53490. this._randomTexture.dispose();
  53491. this._randomTexture = null;
  53492. }
  53493. if (disposeTexture && this.particleTexture) {
  53494. this.particleTexture.dispose();
  53495. this.particleTexture = null;
  53496. }
  53497. // Callback
  53498. this.onDisposeObservable.notifyObservers(this);
  53499. this.onDisposeObservable.clear();
  53500. };
  53501. /**
  53502. * Clones the particle system.
  53503. * @param name The name of the cloned object
  53504. * @param newEmitter The new emitter to use
  53505. * @returns the cloned particle system
  53506. */
  53507. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53508. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53509. BABYLON.Tools.DeepCopy(this, result);
  53510. if (newEmitter === undefined) {
  53511. newEmitter = this.emitter;
  53512. }
  53513. result.emitter = newEmitter;
  53514. if (this.particleTexture) {
  53515. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53516. }
  53517. return result;
  53518. };
  53519. /**
  53520. * Serializes the particle system to a JSON object.
  53521. * @returns the JSON object
  53522. */
  53523. GPUParticleSystem.prototype.serialize = function () {
  53524. var serializationObject = {};
  53525. serializationObject.name = this.name;
  53526. serializationObject.id = this.id;
  53527. // Emitter
  53528. if (this.emitter.position) {
  53529. var emitterMesh = this.emitter;
  53530. serializationObject.emitterId = emitterMesh.id;
  53531. }
  53532. else {
  53533. var emitterPosition = this.emitter;
  53534. serializationObject.emitter = emitterPosition.asArray();
  53535. }
  53536. serializationObject.capacity = this.getCapacity();
  53537. if (this.particleTexture) {
  53538. serializationObject.textureName = this.particleTexture.name;
  53539. }
  53540. // Animations
  53541. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53542. // Particle system
  53543. serializationObject.activeParticleCount = this.activeParticleCount;
  53544. serializationObject.randomTextureSize = this._randomTextureSize;
  53545. serializationObject.minSize = this.minSize;
  53546. serializationObject.maxSize = this.maxSize;
  53547. serializationObject.minEmitPower = this.minEmitPower;
  53548. serializationObject.maxEmitPower = this.maxEmitPower;
  53549. serializationObject.minLifeTime = this.minLifeTime;
  53550. serializationObject.maxLifeTime = this.maxLifeTime;
  53551. serializationObject.emitRate = this.emitRate;
  53552. serializationObject.gravity = this.gravity.asArray();
  53553. serializationObject.color1 = this.color1.asArray();
  53554. serializationObject.color2 = this.color2.asArray();
  53555. serializationObject.colorDead = this.colorDead.asArray();
  53556. serializationObject.updateSpeed = this.updateSpeed;
  53557. serializationObject.targetStopDuration = this.targetStopDuration;
  53558. serializationObject.blendMode = this.blendMode;
  53559. // Emitter
  53560. if (this.particleEmitterType) {
  53561. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53562. }
  53563. return serializationObject;
  53564. };
  53565. /**
  53566. * Parses a JSON object to create a GPU particle system.
  53567. * @param parsedParticleSystem The JSON object to parse
  53568. * @param scene The scene to create the particle system in
  53569. * @param rootUrl The root url to use to load external dependencies like texture
  53570. * @returns the parsed GPU particle system
  53571. */
  53572. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53573. var name = parsedParticleSystem.name;
  53574. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53575. if (parsedParticleSystem.id) {
  53576. particleSystem.id = parsedParticleSystem.id;
  53577. }
  53578. // Texture
  53579. if (parsedParticleSystem.textureName) {
  53580. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53581. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53582. }
  53583. // Emitter
  53584. if (parsedParticleSystem.emitterId) {
  53585. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53586. }
  53587. else {
  53588. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53589. }
  53590. // Animations
  53591. if (parsedParticleSystem.animations) {
  53592. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53593. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53594. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53595. }
  53596. }
  53597. // Particle system
  53598. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53599. particleSystem.minSize = parsedParticleSystem.minSize;
  53600. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53601. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53602. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53603. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53604. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53605. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53606. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53607. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53608. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53609. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53610. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53611. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53612. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53613. // Emitter
  53614. if (parsedParticleSystem.particleEmitterType) {
  53615. var emitterType = void 0;
  53616. switch (parsedParticleSystem.particleEmitterType.type) {
  53617. case "SphereEmitter":
  53618. emitterType = new BABYLON.SphereParticleEmitter();
  53619. break;
  53620. case "SphereDirectedParticleEmitter":
  53621. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53622. break;
  53623. case "ConeEmitter":
  53624. emitterType = new BABYLON.ConeParticleEmitter();
  53625. break;
  53626. case "BoxEmitter":
  53627. default:
  53628. emitterType = new BABYLON.BoxParticleEmitter();
  53629. break;
  53630. }
  53631. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53632. particleSystem.particleEmitterType = emitterType;
  53633. }
  53634. return particleSystem;
  53635. };
  53636. return GPUParticleSystem;
  53637. }());
  53638. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53639. })(BABYLON || (BABYLON = {}));
  53640. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53641. "use strict";
  53642. var BABYLON;
  53643. (function (BABYLON) {
  53644. /**
  53645. * Represents one particle of a solid particle system.
  53646. * @see SolidParticleSystem
  53647. */
  53648. var SolidParticle = /** @class */ (function () {
  53649. /**
  53650. * Creates a Solid Particle object.
  53651. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53652. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53653. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53654. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53655. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53656. * @param shapeId (integer) is the model shape identifier in the SPS.
  53657. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53658. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53659. */
  53660. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53661. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53662. /**
  53663. * particle global index
  53664. */
  53665. this.idx = 0;
  53666. /**
  53667. * The color of the particle
  53668. */
  53669. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53670. /**
  53671. * The world space position of the particle.
  53672. */
  53673. this.position = BABYLON.Vector3.Zero();
  53674. /**
  53675. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53676. */
  53677. this.rotation = BABYLON.Vector3.Zero();
  53678. /**
  53679. * The scaling of the particle.
  53680. */
  53681. this.scaling = BABYLON.Vector3.One();
  53682. /**
  53683. * The uvs of the particle.
  53684. */
  53685. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53686. /**
  53687. * The current speed of the particle.
  53688. */
  53689. this.velocity = BABYLON.Vector3.Zero();
  53690. /**
  53691. * The pivot point in the particle local space.
  53692. */
  53693. this.pivot = BABYLON.Vector3.Zero();
  53694. /**
  53695. * Must the particle be translated from its pivot point in its local space ?
  53696. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53697. * Default : false
  53698. */
  53699. this.translateFromPivot = false;
  53700. /**
  53701. * Is the particle active or not ?
  53702. */
  53703. this.alive = true;
  53704. /**
  53705. * Is the particle visible or not ?
  53706. */
  53707. this.isVisible = true;
  53708. /**
  53709. * Index of this particle in the global "positions" array (Internal use)
  53710. */
  53711. this._pos = 0;
  53712. /**
  53713. * Index of this particle in the global "indices" array (Internal use)
  53714. */
  53715. this._ind = 0;
  53716. /**
  53717. * ModelShape id of this particle
  53718. */
  53719. this.shapeId = 0;
  53720. /**
  53721. * Index of the particle in its shape id (Internal use)
  53722. */
  53723. this.idxInShape = 0;
  53724. /**
  53725. * Still set as invisible in order to skip useless computations (Internal use)
  53726. */
  53727. this._stillInvisible = false;
  53728. /**
  53729. * Last computed particle rotation matrix
  53730. */
  53731. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53732. /**
  53733. * Parent particle Id, if any.
  53734. * Default null.
  53735. */
  53736. this.parentId = null;
  53737. /**
  53738. * Internal global position in the SPS.
  53739. */
  53740. this._globalPosition = BABYLON.Vector3.Zero();
  53741. this.idx = particleIndex;
  53742. this._pos = positionIndex;
  53743. this._ind = indiceIndex;
  53744. this._model = model;
  53745. this.shapeId = shapeId;
  53746. this.idxInShape = idxInShape;
  53747. this._sps = sps;
  53748. if (modelBoundingInfo) {
  53749. this._modelBoundingInfo = modelBoundingInfo;
  53750. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53751. }
  53752. }
  53753. Object.defineProperty(SolidParticle.prototype, "scale", {
  53754. /**
  53755. * Legacy support, changed scale to scaling
  53756. */
  53757. get: function () {
  53758. return this.scaling;
  53759. },
  53760. /**
  53761. * Legacy support, changed scale to scaling
  53762. */
  53763. set: function (scale) {
  53764. this.scaling = scale;
  53765. },
  53766. enumerable: true,
  53767. configurable: true
  53768. });
  53769. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53770. /**
  53771. * Legacy support, changed quaternion to rotationQuaternion
  53772. */
  53773. get: function () {
  53774. return this.rotationQuaternion;
  53775. },
  53776. /**
  53777. * Legacy support, changed quaternion to rotationQuaternion
  53778. */
  53779. set: function (q) {
  53780. this.rotationQuaternion = q;
  53781. },
  53782. enumerable: true,
  53783. configurable: true
  53784. });
  53785. /**
  53786. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53787. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53788. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53789. * @returns true if it intersects
  53790. */
  53791. SolidParticle.prototype.intersectsMesh = function (target) {
  53792. if (!this._boundingInfo || !target._boundingInfo) {
  53793. return false;
  53794. }
  53795. if (this._sps._bSphereOnly) {
  53796. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53797. }
  53798. return this._boundingInfo.intersects(target._boundingInfo, false);
  53799. };
  53800. return SolidParticle;
  53801. }());
  53802. BABYLON.SolidParticle = SolidParticle;
  53803. /**
  53804. * Represents the shape of the model used by one particle of a solid particle system.
  53805. * SPS internal tool, don't use it manually.
  53806. * @see SolidParticleSystem
  53807. */
  53808. var ModelShape = /** @class */ (function () {
  53809. /**
  53810. * 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.
  53811. * SPS internal tool, don't use it manually.
  53812. * @ignore
  53813. */
  53814. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53815. /**
  53816. * length of the shape in the model indices array (internal use)
  53817. */
  53818. this._indicesLength = 0;
  53819. this.shapeID = id;
  53820. this._shape = shape;
  53821. this._indicesLength = indicesLength;
  53822. this._shapeUV = shapeUV;
  53823. this._positionFunction = posFunction;
  53824. this._vertexFunction = vtxFunction;
  53825. }
  53826. return ModelShape;
  53827. }());
  53828. BABYLON.ModelShape = ModelShape;
  53829. /**
  53830. * Represents a Depth Sorted Particle in the solid particle system.
  53831. * @see SolidParticleSystem
  53832. */
  53833. var DepthSortedParticle = /** @class */ (function () {
  53834. function DepthSortedParticle() {
  53835. /**
  53836. * Index of the particle in the "indices" array
  53837. */
  53838. this.ind = 0;
  53839. /**
  53840. * Length of the particle shape in the "indices" array
  53841. */
  53842. this.indicesLength = 0;
  53843. /**
  53844. * Squared distance from the particle to the camera
  53845. */
  53846. this.sqDistance = 0.0;
  53847. }
  53848. return DepthSortedParticle;
  53849. }());
  53850. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53851. })(BABYLON || (BABYLON = {}));
  53852. //# sourceMappingURL=babylon.solidParticle.js.map
  53853. "use strict";
  53854. var BABYLON;
  53855. (function (BABYLON) {
  53856. /**
  53857. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53858. *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.
  53859. * The SPS is also a particle system. It provides some methods to manage the particles.
  53860. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53861. *
  53862. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53863. */
  53864. var SolidParticleSystem = /** @class */ (function () {
  53865. /**
  53866. * Creates a SPS (Solid Particle System) object.
  53867. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53868. * @param scene (Scene) is the scene in which the SPS is added.
  53869. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53870. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53871. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53872. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53873. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53874. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53875. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53876. */
  53877. function SolidParticleSystem(name, scene, options) {
  53878. /**
  53879. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53880. * Example : var p = SPS.particles[i];
  53881. */
  53882. this.particles = new Array();
  53883. /**
  53884. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53885. */
  53886. this.nbParticles = 0;
  53887. /**
  53888. * If the particles must ever face the camera (default false). Useful for planar particles.
  53889. */
  53890. this.billboard = false;
  53891. /**
  53892. * Recompute normals when adding a shape
  53893. */
  53894. this.recomputeNormals = true;
  53895. /**
  53896. * This a counter ofr your own usage. It's not set by any SPS functions.
  53897. */
  53898. this.counter = 0;
  53899. /**
  53900. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53901. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53902. */
  53903. this.vars = {};
  53904. /**
  53905. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53906. */
  53907. this._bSphereOnly = false;
  53908. /**
  53909. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53910. */
  53911. this._bSphereRadiusFactor = 1.0;
  53912. this._positions = new Array();
  53913. this._indices = new Array();
  53914. this._normals = new Array();
  53915. this._colors = new Array();
  53916. this._uvs = new Array();
  53917. this._index = 0; // indices index
  53918. this._updatable = true;
  53919. this._pickable = false;
  53920. this._isVisibilityBoxLocked = false;
  53921. this._alwaysVisible = false;
  53922. this._depthSort = false;
  53923. this._shapeCounter = 0;
  53924. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53925. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53926. this._computeParticleColor = true;
  53927. this._computeParticleTexture = true;
  53928. this._computeParticleRotation = true;
  53929. this._computeParticleVertex = false;
  53930. this._computeBoundingBox = false;
  53931. this._depthSortParticles = true;
  53932. this._cam_axisZ = BABYLON.Vector3.Zero();
  53933. this._cam_axisY = BABYLON.Vector3.Zero();
  53934. this._cam_axisX = BABYLON.Vector3.Zero();
  53935. this._axisZ = BABYLON.Axis.Z;
  53936. this._camDir = BABYLON.Vector3.Zero();
  53937. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53938. this._rotMatrix = new BABYLON.Matrix();
  53939. this._invertMatrix = new BABYLON.Matrix();
  53940. this._rotated = BABYLON.Vector3.Zero();
  53941. this._quaternion = new BABYLON.Quaternion();
  53942. this._vertex = BABYLON.Vector3.Zero();
  53943. this._normal = BABYLON.Vector3.Zero();
  53944. this._yaw = 0.0;
  53945. this._pitch = 0.0;
  53946. this._roll = 0.0;
  53947. this._halfroll = 0.0;
  53948. this._halfpitch = 0.0;
  53949. this._halfyaw = 0.0;
  53950. this._sinRoll = 0.0;
  53951. this._cosRoll = 0.0;
  53952. this._sinPitch = 0.0;
  53953. this._cosPitch = 0.0;
  53954. this._sinYaw = 0.0;
  53955. this._cosYaw = 0.0;
  53956. this._mustUnrotateFixedNormals = false;
  53957. this._minimum = BABYLON.Vector3.Zero();
  53958. this._maximum = BABYLON.Vector3.Zero();
  53959. this._minBbox = BABYLON.Vector3.Zero();
  53960. this._maxBbox = BABYLON.Vector3.Zero();
  53961. this._particlesIntersect = false;
  53962. this._depthSortFunction = function (p1, p2) {
  53963. return (p2.sqDistance - p1.sqDistance);
  53964. };
  53965. this._needs32Bits = false;
  53966. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53967. this._scaledPivot = BABYLON.Vector3.Zero();
  53968. this._particleHasParent = false;
  53969. this.name = name;
  53970. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53971. this._camera = scene.activeCamera;
  53972. this._pickable = options ? options.isPickable : false;
  53973. this._depthSort = options ? options.enableDepthSort : false;
  53974. this._particlesIntersect = options ? options.particleIntersection : false;
  53975. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53976. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53977. if (options && options.updatable) {
  53978. this._updatable = options.updatable;
  53979. }
  53980. else {
  53981. this._updatable = true;
  53982. }
  53983. if (this._pickable) {
  53984. this.pickedParticles = [];
  53985. }
  53986. if (this._depthSort) {
  53987. this.depthSortedParticles = [];
  53988. }
  53989. }
  53990. /**
  53991. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53992. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53993. * @returns the created mesh
  53994. */
  53995. SolidParticleSystem.prototype.buildMesh = function () {
  53996. if (this.nbParticles === 0) {
  53997. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53998. this.addShape(triangle, 1);
  53999. triangle.dispose();
  54000. }
  54001. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54002. this._positions32 = new Float32Array(this._positions);
  54003. this._uvs32 = new Float32Array(this._uvs);
  54004. this._colors32 = new Float32Array(this._colors);
  54005. if (this.recomputeNormals) {
  54006. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54007. }
  54008. this._normals32 = new Float32Array(this._normals);
  54009. this._fixedNormal32 = new Float32Array(this._normals);
  54010. if (this._mustUnrotateFixedNormals) {
  54011. this._unrotateFixedNormals();
  54012. }
  54013. var vertexData = new BABYLON.VertexData();
  54014. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54015. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54016. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54017. if (this._uvs32) {
  54018. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54019. ;
  54020. }
  54021. if (this._colors32) {
  54022. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54023. }
  54024. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54025. vertexData.applyToMesh(mesh, this._updatable);
  54026. this.mesh = mesh;
  54027. this.mesh.isPickable = this._pickable;
  54028. // free memory
  54029. if (!this._depthSort) {
  54030. this._indices = null;
  54031. }
  54032. this._positions = null;
  54033. this._normals = null;
  54034. this._uvs = null;
  54035. this._colors = null;
  54036. if (!this._updatable) {
  54037. this.particles.length = 0;
  54038. }
  54039. return mesh;
  54040. };
  54041. /**
  54042. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54043. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54044. * Thus the particles generated from `digest()` have their property `position` set yet.
  54045. * @param mesh ( Mesh ) is the mesh to be digested
  54046. * @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
  54047. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54048. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54049. * @returns the current SPS
  54050. */
  54051. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54052. var size = (options && options.facetNb) || 1;
  54053. var number = (options && options.number) || 0;
  54054. var delta = (options && options.delta) || 0;
  54055. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54056. var meshInd = mesh.getIndices();
  54057. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54058. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54059. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54060. var f = 0; // facet counter
  54061. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54062. // compute size from number
  54063. if (number) {
  54064. number = (number > totalFacets) ? totalFacets : number;
  54065. size = Math.round(totalFacets / number);
  54066. delta = 0;
  54067. }
  54068. else {
  54069. size = (size > totalFacets) ? totalFacets : size;
  54070. }
  54071. var facetPos = []; // submesh positions
  54072. var facetInd = []; // submesh indices
  54073. var facetUV = []; // submesh UV
  54074. var facetCol = []; // submesh colors
  54075. var barycenter = BABYLON.Vector3.Zero();
  54076. var sizeO = size;
  54077. while (f < totalFacets) {
  54078. size = sizeO + Math.floor((1 + delta) * Math.random());
  54079. if (f > totalFacets - size) {
  54080. size = totalFacets - f;
  54081. }
  54082. // reset temp arrays
  54083. facetPos.length = 0;
  54084. facetInd.length = 0;
  54085. facetUV.length = 0;
  54086. facetCol.length = 0;
  54087. // iterate over "size" facets
  54088. var fi = 0;
  54089. for (var j = f * 3; j < (f + size) * 3; j++) {
  54090. facetInd.push(fi);
  54091. var i = meshInd[j];
  54092. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54093. if (meshUV) {
  54094. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54095. }
  54096. if (meshCol) {
  54097. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54098. }
  54099. fi++;
  54100. }
  54101. // create a model shape for each single particle
  54102. var idx = this.nbParticles;
  54103. var shape = this._posToShape(facetPos);
  54104. var shapeUV = this._uvsToShapeUV(facetUV);
  54105. // compute the barycenter of the shape
  54106. var v;
  54107. for (v = 0; v < shape.length; v++) {
  54108. barycenter.addInPlace(shape[v]);
  54109. }
  54110. barycenter.scaleInPlace(1 / shape.length);
  54111. // shift the shape from its barycenter to the origin
  54112. for (v = 0; v < shape.length; v++) {
  54113. shape[v].subtractInPlace(barycenter);
  54114. }
  54115. var bInfo;
  54116. if (this._particlesIntersect) {
  54117. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54118. }
  54119. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54120. // add the particle in the SPS
  54121. var currentPos = this._positions.length;
  54122. var currentInd = this._indices.length;
  54123. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54124. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54125. // initialize the particle position
  54126. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54127. this._index += shape.length;
  54128. idx++;
  54129. this.nbParticles++;
  54130. this._shapeCounter++;
  54131. f += size;
  54132. }
  54133. return this;
  54134. };
  54135. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54136. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54137. var index = 0;
  54138. var idx = 0;
  54139. for (var p = 0; p < this.particles.length; p++) {
  54140. this._particle = this.particles[p];
  54141. this._shape = this._particle._model._shape;
  54142. if (this._particle.rotationQuaternion) {
  54143. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54144. }
  54145. else {
  54146. this._yaw = this._particle.rotation.y;
  54147. this._pitch = this._particle.rotation.x;
  54148. this._roll = this._particle.rotation.z;
  54149. this._quaternionRotationYPR();
  54150. }
  54151. this._quaternionToRotationMatrix();
  54152. this._rotMatrix.invertToRef(this._invertMatrix);
  54153. for (var pt = 0; pt < this._shape.length; pt++) {
  54154. idx = index + pt * 3;
  54155. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54156. this._fixedNormal32[idx] = this._normal.x;
  54157. this._fixedNormal32[idx + 1] = this._normal.y;
  54158. this._fixedNormal32[idx + 2] = this._normal.z;
  54159. }
  54160. index = idx + 3;
  54161. }
  54162. };
  54163. //reset copy
  54164. SolidParticleSystem.prototype._resetCopy = function () {
  54165. this._copy.position.x = 0;
  54166. this._copy.position.y = 0;
  54167. this._copy.position.z = 0;
  54168. this._copy.rotation.x = 0;
  54169. this._copy.rotation.y = 0;
  54170. this._copy.rotation.z = 0;
  54171. this._copy.rotationQuaternion = null;
  54172. this._copy.scaling.x = 1.0;
  54173. this._copy.scaling.y = 1.0;
  54174. this._copy.scaling.z = 1.0;
  54175. this._copy.uvs.x = 0;
  54176. this._copy.uvs.y = 0;
  54177. this._copy.uvs.z = 1.0;
  54178. this._copy.uvs.w = 1.0;
  54179. this._copy.color = null;
  54180. this._copy.translateFromPivot = false;
  54181. };
  54182. // _meshBuilder : inserts the shape model in the global SPS mesh
  54183. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54184. var i;
  54185. var u = 0;
  54186. var c = 0;
  54187. var n = 0;
  54188. this._resetCopy();
  54189. if (options && options.positionFunction) {
  54190. options.positionFunction(this._copy, idx, idxInShape);
  54191. this._mustUnrotateFixedNormals = true;
  54192. }
  54193. if (this._copy.rotationQuaternion) {
  54194. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54195. }
  54196. else {
  54197. this._yaw = this._copy.rotation.y;
  54198. this._pitch = this._copy.rotation.x;
  54199. this._roll = this._copy.rotation.z;
  54200. this._quaternionRotationYPR();
  54201. }
  54202. this._quaternionToRotationMatrix();
  54203. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54204. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54205. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54206. if (this._copy.translateFromPivot) {
  54207. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54208. }
  54209. else {
  54210. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54211. }
  54212. for (i = 0; i < shape.length; i++) {
  54213. this._vertex.x = shape[i].x;
  54214. this._vertex.y = shape[i].y;
  54215. this._vertex.z = shape[i].z;
  54216. if (options && options.vertexFunction) {
  54217. options.vertexFunction(this._copy, this._vertex, i);
  54218. }
  54219. this._vertex.x *= this._copy.scaling.x;
  54220. this._vertex.y *= this._copy.scaling.y;
  54221. this._vertex.z *= this._copy.scaling.z;
  54222. this._vertex.x -= this._scaledPivot.x;
  54223. this._vertex.y -= this._scaledPivot.y;
  54224. this._vertex.z -= this._scaledPivot.z;
  54225. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54226. this._rotated.addInPlace(this._pivotBackTranslation);
  54227. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54228. if (meshUV) {
  54229. 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);
  54230. u += 2;
  54231. }
  54232. if (this._copy.color) {
  54233. this._color = this._copy.color;
  54234. }
  54235. else if (meshCol && meshCol[c] !== undefined) {
  54236. this._color.r = meshCol[c];
  54237. this._color.g = meshCol[c + 1];
  54238. this._color.b = meshCol[c + 2];
  54239. this._color.a = meshCol[c + 3];
  54240. }
  54241. else {
  54242. this._color.r = 1.0;
  54243. this._color.g = 1.0;
  54244. this._color.b = 1.0;
  54245. this._color.a = 1.0;
  54246. }
  54247. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54248. c += 4;
  54249. if (!this.recomputeNormals && meshNor) {
  54250. this._normal.x = meshNor[n];
  54251. this._normal.y = meshNor[n + 1];
  54252. this._normal.z = meshNor[n + 2];
  54253. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54254. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54255. n += 3;
  54256. }
  54257. }
  54258. for (i = 0; i < meshInd.length; i++) {
  54259. var current_ind = p + meshInd[i];
  54260. indices.push(current_ind);
  54261. if (current_ind > 65535) {
  54262. this._needs32Bits = true;
  54263. }
  54264. }
  54265. if (this._pickable) {
  54266. var nbfaces = meshInd.length / 3;
  54267. for (i = 0; i < nbfaces; i++) {
  54268. this.pickedParticles.push({ idx: idx, faceId: i });
  54269. }
  54270. }
  54271. if (this._depthSort) {
  54272. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54273. }
  54274. return this._copy;
  54275. };
  54276. // returns a shape array from positions array
  54277. SolidParticleSystem.prototype._posToShape = function (positions) {
  54278. var shape = [];
  54279. for (var i = 0; i < positions.length; i += 3) {
  54280. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54281. }
  54282. return shape;
  54283. };
  54284. // returns a shapeUV array from a Vector4 uvs
  54285. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54286. var shapeUV = [];
  54287. if (uvs) {
  54288. for (var i = 0; i < uvs.length; i++)
  54289. shapeUV.push(uvs[i]);
  54290. }
  54291. return shapeUV;
  54292. };
  54293. // adds a new particle object in the particles array
  54294. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54295. if (bInfo === void 0) { bInfo = null; }
  54296. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54297. this.particles.push(sp);
  54298. return sp;
  54299. };
  54300. /**
  54301. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54302. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54303. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54304. * @param nb (positive integer) the number of particles to be created from this model
  54305. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54306. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54307. * @returns the number of shapes in the system
  54308. */
  54309. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54310. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54311. var meshInd = mesh.getIndices();
  54312. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54313. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54314. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54315. var bbInfo;
  54316. if (this._particlesIntersect) {
  54317. bbInfo = mesh.getBoundingInfo();
  54318. }
  54319. var shape = this._posToShape(meshPos);
  54320. var shapeUV = this._uvsToShapeUV(meshUV);
  54321. var posfunc = options ? options.positionFunction : null;
  54322. var vtxfunc = options ? options.vertexFunction : null;
  54323. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54324. // particles
  54325. var sp;
  54326. var currentCopy;
  54327. var idx = this.nbParticles;
  54328. for (var i = 0; i < nb; i++) {
  54329. var currentPos = this._positions.length;
  54330. var currentInd = this._indices.length;
  54331. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54332. if (this._updatable) {
  54333. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54334. sp.position.copyFrom(currentCopy.position);
  54335. sp.rotation.copyFrom(currentCopy.rotation);
  54336. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54337. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54338. }
  54339. if (currentCopy.color && sp.color) {
  54340. sp.color.copyFrom(currentCopy.color);
  54341. }
  54342. sp.scaling.copyFrom(currentCopy.scaling);
  54343. sp.uvs.copyFrom(currentCopy.uvs);
  54344. }
  54345. this._index += shape.length;
  54346. idx++;
  54347. }
  54348. this.nbParticles += nb;
  54349. this._shapeCounter++;
  54350. return this._shapeCounter - 1;
  54351. };
  54352. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54353. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54354. this._resetCopy();
  54355. if (particle._model._positionFunction) {
  54356. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54357. }
  54358. if (this._copy.rotationQuaternion) {
  54359. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54360. }
  54361. else {
  54362. this._yaw = this._copy.rotation.y;
  54363. this._pitch = this._copy.rotation.x;
  54364. this._roll = this._copy.rotation.z;
  54365. this._quaternionRotationYPR();
  54366. }
  54367. this._quaternionToRotationMatrix();
  54368. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54369. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54370. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54371. if (this._copy.translateFromPivot) {
  54372. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54373. }
  54374. else {
  54375. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54376. }
  54377. this._shape = particle._model._shape;
  54378. for (var pt = 0; pt < this._shape.length; pt++) {
  54379. this._vertex.x = this._shape[pt].x;
  54380. this._vertex.y = this._shape[pt].y;
  54381. this._vertex.z = this._shape[pt].z;
  54382. if (particle._model._vertexFunction) {
  54383. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54384. }
  54385. this._vertex.x *= this._copy.scaling.x;
  54386. this._vertex.y *= this._copy.scaling.y;
  54387. this._vertex.z *= this._copy.scaling.z;
  54388. this._vertex.x -= this._scaledPivot.x;
  54389. this._vertex.y -= this._scaledPivot.y;
  54390. this._vertex.z -= this._scaledPivot.z;
  54391. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54392. this._rotated.addInPlace(this._pivotBackTranslation);
  54393. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54394. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54395. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54396. }
  54397. particle.position.x = 0.0;
  54398. particle.position.y = 0.0;
  54399. particle.position.z = 0.0;
  54400. particle.rotation.x = 0.0;
  54401. particle.rotation.y = 0.0;
  54402. particle.rotation.z = 0.0;
  54403. particle.rotationQuaternion = null;
  54404. particle.scaling.x = 1.0;
  54405. particle.scaling.y = 1.0;
  54406. particle.scaling.z = 1.0;
  54407. particle.uvs.x = 0.0;
  54408. particle.uvs.y = 0.0;
  54409. particle.uvs.z = 1.0;
  54410. particle.uvs.w = 1.0;
  54411. particle.pivot.x = 0.0;
  54412. particle.pivot.y = 0.0;
  54413. particle.pivot.z = 0.0;
  54414. particle.translateFromPivot = false;
  54415. particle.parentId = null;
  54416. };
  54417. /**
  54418. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54419. * @returns the SPS.
  54420. */
  54421. SolidParticleSystem.prototype.rebuildMesh = function () {
  54422. for (var p = 0; p < this.particles.length; p++) {
  54423. this._rebuildParticle(this.particles[p]);
  54424. }
  54425. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54426. return this;
  54427. };
  54428. /**
  54429. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54430. * This method calls `updateParticle()` for each particle of the SPS.
  54431. * For an animated SPS, it is usually called within the render loop.
  54432. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54433. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54434. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54435. * @returns the SPS.
  54436. */
  54437. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54438. if (start === void 0) { start = 0; }
  54439. if (end === void 0) { end = this.nbParticles - 1; }
  54440. if (update === void 0) { update = true; }
  54441. if (!this._updatable) {
  54442. return this;
  54443. }
  54444. // custom beforeUpdate
  54445. this.beforeUpdateParticles(start, end, update);
  54446. this._cam_axisX.x = 1.0;
  54447. this._cam_axisX.y = 0.0;
  54448. this._cam_axisX.z = 0.0;
  54449. this._cam_axisY.x = 0.0;
  54450. this._cam_axisY.y = 1.0;
  54451. this._cam_axisY.z = 0.0;
  54452. this._cam_axisZ.x = 0.0;
  54453. this._cam_axisZ.y = 0.0;
  54454. this._cam_axisZ.z = 1.0;
  54455. // cases when the World Matrix is to be computed first
  54456. if (this.billboard || this._depthSort) {
  54457. this.mesh.computeWorldMatrix(true);
  54458. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54459. }
  54460. // if the particles will always face the camera
  54461. if (this.billboard) {
  54462. // compute the camera position and un-rotate it by the current mesh rotation
  54463. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54464. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54465. this._cam_axisZ.normalize();
  54466. // same for camera up vector extracted from the cam view matrix
  54467. var view = this._camera.getViewMatrix(true);
  54468. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54469. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54470. this._cam_axisY.normalize();
  54471. this._cam_axisX.normalize();
  54472. }
  54473. // if depthSort, compute the camera global position in the mesh local system
  54474. if (this._depthSort) {
  54475. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54476. }
  54477. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54478. var idx = 0; // current position index in the global array positions32
  54479. var index = 0; // position start index in the global array positions32 of the current particle
  54480. var colidx = 0; // current color index in the global array colors32
  54481. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54482. var uvidx = 0; // current uv index in the global array uvs32
  54483. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54484. var pt = 0; // current index in the particle model shape
  54485. if (this.mesh.isFacetDataEnabled) {
  54486. this._computeBoundingBox = true;
  54487. }
  54488. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54489. if (this._computeBoundingBox) {
  54490. if (start == 0 && end == this.nbParticles - 1) {
  54491. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54492. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54493. }
  54494. else {
  54495. if (this.mesh._boundingInfo) {
  54496. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54497. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54498. }
  54499. }
  54500. }
  54501. // particle loop
  54502. index = this.particles[start]._pos;
  54503. var vpos = (index / 3) | 0;
  54504. colorIndex = vpos * 4;
  54505. uvIndex = vpos * 2;
  54506. for (var p = start; p <= end; p++) {
  54507. this._particle = this.particles[p];
  54508. this._shape = this._particle._model._shape;
  54509. this._shapeUV = this._particle._model._shapeUV;
  54510. // call to custom user function to update the particle properties
  54511. this.updateParticle(this._particle);
  54512. // camera-particle distance for depth sorting
  54513. if (this._depthSort && this._depthSortParticles) {
  54514. var dsp = this.depthSortedParticles[p];
  54515. dsp.ind = this._particle._ind;
  54516. dsp.indicesLength = this._particle._model._indicesLength;
  54517. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54518. }
  54519. // skip the computations for inactive or already invisible particles
  54520. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54521. // increment indexes for the next particle
  54522. pt = this._shape.length;
  54523. index += pt * 3;
  54524. colorIndex += pt * 4;
  54525. uvIndex += pt * 2;
  54526. continue;
  54527. }
  54528. if (this._particle.isVisible) {
  54529. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54530. this._particleHasParent = (this._particle.parentId !== null);
  54531. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54532. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54533. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54534. // particle rotation matrix
  54535. if (this.billboard) {
  54536. this._particle.rotation.x = 0.0;
  54537. this._particle.rotation.y = 0.0;
  54538. }
  54539. if (this._computeParticleRotation || this.billboard) {
  54540. if (this._particle.rotationQuaternion) {
  54541. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54542. }
  54543. else {
  54544. this._yaw = this._particle.rotation.y;
  54545. this._pitch = this._particle.rotation.x;
  54546. this._roll = this._particle.rotation.z;
  54547. this._quaternionRotationYPR();
  54548. }
  54549. this._quaternionToRotationMatrix();
  54550. }
  54551. if (this._particleHasParent) {
  54552. this._parent = this.particles[this._particle.parentId];
  54553. 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];
  54554. 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];
  54555. 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];
  54556. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54557. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54558. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54559. if (this._computeParticleRotation || this.billboard) {
  54560. 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];
  54561. 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];
  54562. 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];
  54563. 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];
  54564. 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];
  54565. 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];
  54566. 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];
  54567. 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];
  54568. 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];
  54569. }
  54570. }
  54571. else {
  54572. this._particle._globalPosition.x = this._particle.position.x;
  54573. this._particle._globalPosition.y = this._particle.position.y;
  54574. this._particle._globalPosition.z = this._particle.position.z;
  54575. if (this._computeParticleRotation || this.billboard) {
  54576. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54577. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54578. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54579. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54580. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54581. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54582. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54583. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54584. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54585. }
  54586. }
  54587. if (this._particle.translateFromPivot) {
  54588. this._pivotBackTranslation.x = 0.0;
  54589. this._pivotBackTranslation.y = 0.0;
  54590. this._pivotBackTranslation.z = 0.0;
  54591. }
  54592. else {
  54593. this._pivotBackTranslation.x = this._scaledPivot.x;
  54594. this._pivotBackTranslation.y = this._scaledPivot.y;
  54595. this._pivotBackTranslation.z = this._scaledPivot.z;
  54596. }
  54597. // particle vertex loop
  54598. for (pt = 0; pt < this._shape.length; pt++) {
  54599. idx = index + pt * 3;
  54600. colidx = colorIndex + pt * 4;
  54601. uvidx = uvIndex + pt * 2;
  54602. this._vertex.x = this._shape[pt].x;
  54603. this._vertex.y = this._shape[pt].y;
  54604. this._vertex.z = this._shape[pt].z;
  54605. if (this._computeParticleVertex) {
  54606. this.updateParticleVertex(this._particle, this._vertex, pt);
  54607. }
  54608. // positions
  54609. this._vertex.x *= this._particle.scaling.x;
  54610. this._vertex.y *= this._particle.scaling.y;
  54611. this._vertex.z *= this._particle.scaling.z;
  54612. this._vertex.x -= this._scaledPivot.x;
  54613. this._vertex.y -= this._scaledPivot.y;
  54614. this._vertex.z -= this._scaledPivot.z;
  54615. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54616. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54617. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54618. this._rotated.x += this._pivotBackTranslation.x;
  54619. this._rotated.y += this._pivotBackTranslation.y;
  54620. this._rotated.z += this._pivotBackTranslation.z;
  54621. 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;
  54622. 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;
  54623. 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;
  54624. if (this._computeBoundingBox) {
  54625. if (this._positions32[idx] < this._minimum.x) {
  54626. this._minimum.x = this._positions32[idx];
  54627. }
  54628. if (this._positions32[idx] > this._maximum.x) {
  54629. this._maximum.x = this._positions32[idx];
  54630. }
  54631. if (this._positions32[idx + 1] < this._minimum.y) {
  54632. this._minimum.y = this._positions32[idx + 1];
  54633. }
  54634. if (this._positions32[idx + 1] > this._maximum.y) {
  54635. this._maximum.y = this._positions32[idx + 1];
  54636. }
  54637. if (this._positions32[idx + 2] < this._minimum.z) {
  54638. this._minimum.z = this._positions32[idx + 2];
  54639. }
  54640. if (this._positions32[idx + 2] > this._maximum.z) {
  54641. this._maximum.z = this._positions32[idx + 2];
  54642. }
  54643. }
  54644. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54645. if (!this._computeParticleVertex) {
  54646. this._normal.x = this._fixedNormal32[idx];
  54647. this._normal.y = this._fixedNormal32[idx + 1];
  54648. this._normal.z = this._fixedNormal32[idx + 2];
  54649. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54650. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54651. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54652. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54653. 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;
  54654. 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;
  54655. }
  54656. if (this._computeParticleColor && this._particle.color) {
  54657. this._colors32[colidx] = this._particle.color.r;
  54658. this._colors32[colidx + 1] = this._particle.color.g;
  54659. this._colors32[colidx + 2] = this._particle.color.b;
  54660. this._colors32[colidx + 3] = this._particle.color.a;
  54661. }
  54662. if (this._computeParticleTexture) {
  54663. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54664. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54665. }
  54666. }
  54667. }
  54668. else {
  54669. this._particle._stillInvisible = true; // mark the particle as invisible
  54670. for (pt = 0; pt < this._shape.length; pt++) {
  54671. idx = index + pt * 3;
  54672. colidx = colorIndex + pt * 4;
  54673. uvidx = uvIndex + pt * 2;
  54674. this._positions32[idx] = 0.0;
  54675. this._positions32[idx + 1] = 0.0;
  54676. this._positions32[idx + 2] = 0.0;
  54677. this._normals32[idx] = 0.0;
  54678. this._normals32[idx + 1] = 0.0;
  54679. this._normals32[idx + 2] = 0.0;
  54680. if (this._computeParticleColor && this._particle.color) {
  54681. this._colors32[colidx] = this._particle.color.r;
  54682. this._colors32[colidx + 1] = this._particle.color.g;
  54683. this._colors32[colidx + 2] = this._particle.color.b;
  54684. this._colors32[colidx + 3] = this._particle.color.a;
  54685. }
  54686. if (this._computeParticleTexture) {
  54687. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54688. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54689. }
  54690. }
  54691. }
  54692. // if the particle intersections must be computed : update the bbInfo
  54693. if (this._particlesIntersect) {
  54694. var bInfo = this._particle._boundingInfo;
  54695. var bBox = bInfo.boundingBox;
  54696. var bSphere = bInfo.boundingSphere;
  54697. if (!this._bSphereOnly) {
  54698. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54699. for (var b = 0; b < bBox.vectors.length; b++) {
  54700. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54701. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54702. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54703. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54704. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54705. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54706. 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;
  54707. 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;
  54708. 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;
  54709. }
  54710. bBox._update(this.mesh._worldMatrix);
  54711. }
  54712. // place and scale the particle bouding sphere in the SPS local system, then update it
  54713. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54714. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54715. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54716. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54717. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54718. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54719. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54720. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54721. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54722. 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));
  54723. bSphere._update(this.mesh._worldMatrix);
  54724. }
  54725. // increment indexes for the next particle
  54726. index = idx + 3;
  54727. colorIndex = colidx + 4;
  54728. uvIndex = uvidx + 2;
  54729. }
  54730. // if the VBO must be updated
  54731. if (update) {
  54732. if (this._computeParticleColor) {
  54733. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54734. }
  54735. if (this._computeParticleTexture) {
  54736. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54737. }
  54738. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54739. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54740. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54741. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54742. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54743. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54744. for (var i = 0; i < this._normals32.length; i++) {
  54745. this._fixedNormal32[i] = this._normals32[i];
  54746. }
  54747. }
  54748. if (!this.mesh.areNormalsFrozen) {
  54749. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54750. }
  54751. }
  54752. if (this._depthSort && this._depthSortParticles) {
  54753. this.depthSortedParticles.sort(this._depthSortFunction);
  54754. var dspl = this.depthSortedParticles.length;
  54755. var sorted = 0;
  54756. var lind = 0;
  54757. var sind = 0;
  54758. var sid = 0;
  54759. for (sorted = 0; sorted < dspl; sorted++) {
  54760. lind = this.depthSortedParticles[sorted].indicesLength;
  54761. sind = this.depthSortedParticles[sorted].ind;
  54762. for (var i = 0; i < lind; i++) {
  54763. this._indices32[sid] = this._indices[sind + i];
  54764. sid++;
  54765. }
  54766. }
  54767. this.mesh.updateIndices(this._indices32);
  54768. }
  54769. }
  54770. if (this._computeBoundingBox) {
  54771. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54772. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54773. }
  54774. this.afterUpdateParticles(start, end, update);
  54775. return this;
  54776. };
  54777. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54778. this._halfroll = this._roll * 0.5;
  54779. this._halfpitch = this._pitch * 0.5;
  54780. this._halfyaw = this._yaw * 0.5;
  54781. this._sinRoll = Math.sin(this._halfroll);
  54782. this._cosRoll = Math.cos(this._halfroll);
  54783. this._sinPitch = Math.sin(this._halfpitch);
  54784. this._cosPitch = Math.cos(this._halfpitch);
  54785. this._sinYaw = Math.sin(this._halfyaw);
  54786. this._cosYaw = Math.cos(this._halfyaw);
  54787. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54788. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54789. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54790. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54791. };
  54792. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54793. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54794. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54795. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54796. this._rotMatrix.m[3] = 0;
  54797. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54798. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54799. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54800. this._rotMatrix.m[7] = 0;
  54801. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54802. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54803. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54804. this._rotMatrix.m[11] = 0;
  54805. this._rotMatrix.m[12] = 0;
  54806. this._rotMatrix.m[13] = 0;
  54807. this._rotMatrix.m[14] = 0;
  54808. this._rotMatrix.m[15] = 1.0;
  54809. };
  54810. /**
  54811. * Disposes the SPS.
  54812. */
  54813. SolidParticleSystem.prototype.dispose = function () {
  54814. this.mesh.dispose();
  54815. this.vars = null;
  54816. // drop references to internal big arrays for the GC
  54817. this._positions = null;
  54818. this._indices = null;
  54819. this._normals = null;
  54820. this._uvs = null;
  54821. this._colors = null;
  54822. this._indices32 = null;
  54823. this._positions32 = null;
  54824. this._normals32 = null;
  54825. this._fixedNormal32 = null;
  54826. this._uvs32 = null;
  54827. this._colors32 = null;
  54828. this.pickedParticles = null;
  54829. };
  54830. /**
  54831. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54832. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54833. * @returns the SPS.
  54834. */
  54835. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54836. if (!this._isVisibilityBoxLocked) {
  54837. this.mesh.refreshBoundingInfo();
  54838. }
  54839. return this;
  54840. };
  54841. /**
  54842. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54843. * @param size the size (float) of the visibility box
  54844. * note : this doesn't lock the SPS mesh bounding box.
  54845. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54846. */
  54847. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54848. var vis = size / 2;
  54849. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54850. };
  54851. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54852. /**
  54853. * Gets whether the SPS as always visible or not
  54854. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54855. */
  54856. get: function () {
  54857. return this._alwaysVisible;
  54858. },
  54859. /**
  54860. * Sets the SPS as always visible or not
  54861. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54862. */
  54863. set: function (val) {
  54864. this._alwaysVisible = val;
  54865. this.mesh.alwaysSelectAsActiveMesh = val;
  54866. },
  54867. enumerable: true,
  54868. configurable: true
  54869. });
  54870. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54871. /**
  54872. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54873. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54874. */
  54875. get: function () {
  54876. return this._isVisibilityBoxLocked;
  54877. },
  54878. /**
  54879. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54880. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54881. */
  54882. set: function (val) {
  54883. this._isVisibilityBoxLocked = val;
  54884. var boundingInfo = this.mesh.getBoundingInfo();
  54885. boundingInfo.isLocked = val;
  54886. },
  54887. enumerable: true,
  54888. configurable: true
  54889. });
  54890. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54891. /**
  54892. * Gets if `setParticles()` computes the particle rotations or not.
  54893. * Default value : true. The SPS is faster when it's set to false.
  54894. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54895. */
  54896. get: function () {
  54897. return this._computeParticleRotation;
  54898. },
  54899. /**
  54900. * Tells to `setParticles()` to compute the particle rotations or not.
  54901. * Default value : true. The SPS is faster when it's set to false.
  54902. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54903. */
  54904. set: function (val) {
  54905. this._computeParticleRotation = val;
  54906. },
  54907. enumerable: true,
  54908. configurable: true
  54909. });
  54910. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54911. /**
  54912. * Gets if `setParticles()` computes the particle colors or not.
  54913. * Default value : true. The SPS is faster when it's set to false.
  54914. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54915. */
  54916. get: function () {
  54917. return this._computeParticleColor;
  54918. },
  54919. /**
  54920. * Tells to `setParticles()` to compute the particle colors or not.
  54921. * Default value : true. The SPS is faster when it's set to false.
  54922. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54923. */
  54924. set: function (val) {
  54925. this._computeParticleColor = val;
  54926. },
  54927. enumerable: true,
  54928. configurable: true
  54929. });
  54930. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54931. /**
  54932. * Gets if `setParticles()` computes the particle textures or not.
  54933. * Default value : true. The SPS is faster when it's set to false.
  54934. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54935. */
  54936. get: function () {
  54937. return this._computeParticleTexture;
  54938. },
  54939. set: function (val) {
  54940. this._computeParticleTexture = val;
  54941. },
  54942. enumerable: true,
  54943. configurable: true
  54944. });
  54945. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54946. /**
  54947. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54948. * Default value : false. The SPS is faster when it's set to false.
  54949. * Note : the particle custom vertex positions aren't stored values.
  54950. */
  54951. get: function () {
  54952. return this._computeParticleVertex;
  54953. },
  54954. /**
  54955. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54956. * Default value : false. The SPS is faster when it's set to false.
  54957. * Note : the particle custom vertex positions aren't stored values.
  54958. */
  54959. set: function (val) {
  54960. this._computeParticleVertex = val;
  54961. },
  54962. enumerable: true,
  54963. configurable: true
  54964. });
  54965. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54966. /**
  54967. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54968. */
  54969. get: function () {
  54970. return this._computeBoundingBox;
  54971. },
  54972. /**
  54973. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54974. */
  54975. set: function (val) {
  54976. this._computeBoundingBox = val;
  54977. },
  54978. enumerable: true,
  54979. configurable: true
  54980. });
  54981. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54982. /**
  54983. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54984. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54985. * Default : `true`
  54986. */
  54987. get: function () {
  54988. return this._depthSortParticles;
  54989. },
  54990. /**
  54991. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54992. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54993. * Default : `true`
  54994. */
  54995. set: function (val) {
  54996. this._depthSortParticles = val;
  54997. },
  54998. enumerable: true,
  54999. configurable: true
  55000. });
  55001. // =======================================================================
  55002. // Particle behavior logic
  55003. // these following methods may be overwritten by the user to fit his needs
  55004. /**
  55005. * This function does nothing. It may be overwritten to set all the particle first values.
  55006. * The SPS doesn't call this function, you may have to call it by your own.
  55007. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55008. */
  55009. SolidParticleSystem.prototype.initParticles = function () {
  55010. };
  55011. /**
  55012. * This function does nothing. It may be overwritten to recycle a particle.
  55013. * The SPS doesn't call this function, you may have to call it by your own.
  55014. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55015. * @param particle The particle to recycle
  55016. * @returns the recycled particle
  55017. */
  55018. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55019. return particle;
  55020. };
  55021. /**
  55022. * Updates a particle : this function should be overwritten by the user.
  55023. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55024. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55025. * @example : just set a particle position or velocity and recycle conditions
  55026. * @param particle The particle to update
  55027. * @returns the updated particle
  55028. */
  55029. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55030. return particle;
  55031. };
  55032. /**
  55033. * Updates a vertex of a particle : it can be overwritten by the user.
  55034. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55035. * @param particle the current particle
  55036. * @param vertex the current index of the current particle
  55037. * @param pt the index of the current vertex in the particle shape
  55038. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55039. * @example : just set a vertex particle position
  55040. * @returns the updated vertex
  55041. */
  55042. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55043. return vertex;
  55044. };
  55045. /**
  55046. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55047. * This does nothing and may be overwritten by the user.
  55048. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55049. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55050. * @param update the boolean update value actually passed to setParticles()
  55051. */
  55052. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55053. };
  55054. /**
  55055. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55056. * This will be passed three parameters.
  55057. * This does nothing and may be overwritten by the user.
  55058. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55059. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55060. * @param update the boolean update value actually passed to setParticles()
  55061. */
  55062. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55063. };
  55064. return SolidParticleSystem;
  55065. }());
  55066. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55067. })(BABYLON || (BABYLON = {}));
  55068. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55069. "use strict";
  55070. var BABYLON;
  55071. (function (BABYLON) {
  55072. var ShaderMaterial = /** @class */ (function (_super) {
  55073. __extends(ShaderMaterial, _super);
  55074. function ShaderMaterial(name, scene, shaderPath, options) {
  55075. var _this = _super.call(this, name, scene) || this;
  55076. _this._textures = {};
  55077. _this._textureArrays = {};
  55078. _this._floats = {};
  55079. _this._ints = {};
  55080. _this._floatsArrays = {};
  55081. _this._colors3 = {};
  55082. _this._colors3Arrays = {};
  55083. _this._colors4 = {};
  55084. _this._vectors2 = {};
  55085. _this._vectors3 = {};
  55086. _this._vectors4 = {};
  55087. _this._matrices = {};
  55088. _this._matrices3x3 = {};
  55089. _this._matrices2x2 = {};
  55090. _this._vectors2Arrays = {};
  55091. _this._vectors3Arrays = {};
  55092. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55093. _this._shaderPath = shaderPath;
  55094. options.needAlphaBlending = options.needAlphaBlending || false;
  55095. options.needAlphaTesting = options.needAlphaTesting || false;
  55096. options.attributes = options.attributes || ["position", "normal", "uv"];
  55097. options.uniforms = options.uniforms || ["worldViewProjection"];
  55098. options.uniformBuffers = options.uniformBuffers || [];
  55099. options.samplers = options.samplers || [];
  55100. options.defines = options.defines || [];
  55101. _this._options = options;
  55102. return _this;
  55103. }
  55104. ShaderMaterial.prototype.getClassName = function () {
  55105. return "ShaderMaterial";
  55106. };
  55107. ShaderMaterial.prototype.needAlphaBlending = function () {
  55108. return this._options.needAlphaBlending;
  55109. };
  55110. ShaderMaterial.prototype.needAlphaTesting = function () {
  55111. return this._options.needAlphaTesting;
  55112. };
  55113. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55114. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55115. this._options.uniforms.push(uniformName);
  55116. }
  55117. };
  55118. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55119. if (this._options.samplers.indexOf(name) === -1) {
  55120. this._options.samplers.push(name);
  55121. }
  55122. this._textures[name] = texture;
  55123. return this;
  55124. };
  55125. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55126. if (this._options.samplers.indexOf(name) === -1) {
  55127. this._options.samplers.push(name);
  55128. }
  55129. this._checkUniform(name);
  55130. this._textureArrays[name] = textures;
  55131. return this;
  55132. };
  55133. ShaderMaterial.prototype.setFloat = function (name, value) {
  55134. this._checkUniform(name);
  55135. this._floats[name] = value;
  55136. return this;
  55137. };
  55138. ShaderMaterial.prototype.setInt = function (name, value) {
  55139. this._checkUniform(name);
  55140. this._ints[name] = value;
  55141. return this;
  55142. };
  55143. ShaderMaterial.prototype.setFloats = function (name, value) {
  55144. this._checkUniform(name);
  55145. this._floatsArrays[name] = value;
  55146. return this;
  55147. };
  55148. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55149. this._checkUniform(name);
  55150. this._colors3[name] = value;
  55151. return this;
  55152. };
  55153. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55154. this._checkUniform(name);
  55155. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55156. color.toArray(arr, arr.length);
  55157. return arr;
  55158. }, []);
  55159. return this;
  55160. };
  55161. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55162. this._checkUniform(name);
  55163. this._colors4[name] = value;
  55164. return this;
  55165. };
  55166. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55167. this._checkUniform(name);
  55168. this._vectors2[name] = value;
  55169. return this;
  55170. };
  55171. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55172. this._checkUniform(name);
  55173. this._vectors3[name] = value;
  55174. return this;
  55175. };
  55176. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55177. this._checkUniform(name);
  55178. this._vectors4[name] = value;
  55179. return this;
  55180. };
  55181. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55182. this._checkUniform(name);
  55183. this._matrices[name] = value;
  55184. return this;
  55185. };
  55186. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55187. this._checkUniform(name);
  55188. this._matrices3x3[name] = value;
  55189. return this;
  55190. };
  55191. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55192. this._checkUniform(name);
  55193. this._matrices2x2[name] = value;
  55194. return this;
  55195. };
  55196. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55197. this._checkUniform(name);
  55198. this._vectors2Arrays[name] = value;
  55199. return this;
  55200. };
  55201. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55202. this._checkUniform(name);
  55203. this._vectors3Arrays[name] = value;
  55204. return this;
  55205. };
  55206. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55207. if (!mesh) {
  55208. return true;
  55209. }
  55210. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55211. return false;
  55212. }
  55213. return false;
  55214. };
  55215. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55216. var scene = this.getScene();
  55217. var engine = scene.getEngine();
  55218. if (!this.checkReadyOnEveryCall) {
  55219. if (this._renderId === scene.getRenderId()) {
  55220. if (this._checkCache(scene, mesh, useInstances)) {
  55221. return true;
  55222. }
  55223. }
  55224. }
  55225. // Instances
  55226. var defines = [];
  55227. var attribs = [];
  55228. var fallbacks = new BABYLON.EffectFallbacks();
  55229. if (useInstances) {
  55230. defines.push("#define INSTANCES");
  55231. }
  55232. for (var index = 0; index < this._options.defines.length; index++) {
  55233. defines.push(this._options.defines[index]);
  55234. }
  55235. for (var index = 0; index < this._options.attributes.length; index++) {
  55236. attribs.push(this._options.attributes[index]);
  55237. }
  55238. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55239. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55240. defines.push("#define VERTEXCOLOR");
  55241. }
  55242. // Bones
  55243. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55244. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55245. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55246. if (mesh.numBoneInfluencers > 4) {
  55247. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55248. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55249. }
  55250. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55251. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55252. fallbacks.addCPUSkinningFallback(0, mesh);
  55253. if (this._options.uniforms.indexOf("mBones") === -1) {
  55254. this._options.uniforms.push("mBones");
  55255. }
  55256. }
  55257. else {
  55258. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55259. }
  55260. // Textures
  55261. for (var name in this._textures) {
  55262. if (!this._textures[name].isReady()) {
  55263. return false;
  55264. }
  55265. }
  55266. // Alpha test
  55267. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55268. defines.push("#define ALPHATEST");
  55269. }
  55270. var previousEffect = this._effect;
  55271. var join = defines.join("\n");
  55272. this._effect = engine.createEffect(this._shaderPath, {
  55273. attributes: attribs,
  55274. uniformsNames: this._options.uniforms,
  55275. uniformBuffersNames: this._options.uniformBuffers,
  55276. samplers: this._options.samplers,
  55277. defines: join,
  55278. fallbacks: fallbacks,
  55279. onCompiled: this.onCompiled,
  55280. onError: this.onError
  55281. }, engine);
  55282. if (!this._effect.isReady()) {
  55283. return false;
  55284. }
  55285. if (previousEffect !== this._effect) {
  55286. scene.resetCachedMaterial();
  55287. }
  55288. this._renderId = scene.getRenderId();
  55289. return true;
  55290. };
  55291. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55292. var scene = this.getScene();
  55293. if (!this._effect) {
  55294. return;
  55295. }
  55296. if (this._options.uniforms.indexOf("world") !== -1) {
  55297. this._effect.setMatrix("world", world);
  55298. }
  55299. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55300. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55301. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55302. }
  55303. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55304. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55305. }
  55306. };
  55307. ShaderMaterial.prototype.bind = function (world, mesh) {
  55308. // Std values
  55309. this.bindOnlyWorldMatrix(world);
  55310. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55311. if (this._options.uniforms.indexOf("view") !== -1) {
  55312. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55313. }
  55314. if (this._options.uniforms.indexOf("projection") !== -1) {
  55315. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55316. }
  55317. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55318. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55319. }
  55320. // Bones
  55321. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55322. var name;
  55323. // Texture
  55324. for (name in this._textures) {
  55325. this._effect.setTexture(name, this._textures[name]);
  55326. }
  55327. // Texture arrays
  55328. for (name in this._textureArrays) {
  55329. this._effect.setTextureArray(name, this._textureArrays[name]);
  55330. }
  55331. // Int
  55332. for (name in this._ints) {
  55333. this._effect.setInt(name, this._ints[name]);
  55334. }
  55335. // Float
  55336. for (name in this._floats) {
  55337. this._effect.setFloat(name, this._floats[name]);
  55338. }
  55339. // Floats
  55340. for (name in this._floatsArrays) {
  55341. this._effect.setArray(name, this._floatsArrays[name]);
  55342. }
  55343. // Color3
  55344. for (name in this._colors3) {
  55345. this._effect.setColor3(name, this._colors3[name]);
  55346. }
  55347. for (name in this._colors3Arrays) {
  55348. this._effect.setArray3(name, this._colors3Arrays[name]);
  55349. }
  55350. // Color4
  55351. for (name in this._colors4) {
  55352. var color = this._colors4[name];
  55353. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55354. }
  55355. // Vector2
  55356. for (name in this._vectors2) {
  55357. this._effect.setVector2(name, this._vectors2[name]);
  55358. }
  55359. // Vector3
  55360. for (name in this._vectors3) {
  55361. this._effect.setVector3(name, this._vectors3[name]);
  55362. }
  55363. // Vector4
  55364. for (name in this._vectors4) {
  55365. this._effect.setVector4(name, this._vectors4[name]);
  55366. }
  55367. // Matrix
  55368. for (name in this._matrices) {
  55369. this._effect.setMatrix(name, this._matrices[name]);
  55370. }
  55371. // Matrix 3x3
  55372. for (name in this._matrices3x3) {
  55373. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55374. }
  55375. // Matrix 2x2
  55376. for (name in this._matrices2x2) {
  55377. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55378. }
  55379. // Vector2Array
  55380. for (name in this._vectors2Arrays) {
  55381. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55382. }
  55383. // Vector3Array
  55384. for (name in this._vectors3Arrays) {
  55385. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55386. }
  55387. }
  55388. this._afterBind(mesh);
  55389. };
  55390. ShaderMaterial.prototype.getActiveTextures = function () {
  55391. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55392. for (var name in this._textures) {
  55393. activeTextures.push(this._textures[name]);
  55394. }
  55395. for (var name in this._textureArrays) {
  55396. var array = this._textureArrays[name];
  55397. for (var index = 0; index < array.length; index++) {
  55398. activeTextures.push(array[index]);
  55399. }
  55400. }
  55401. return activeTextures;
  55402. };
  55403. ShaderMaterial.prototype.hasTexture = function (texture) {
  55404. if (_super.prototype.hasTexture.call(this, texture)) {
  55405. return true;
  55406. }
  55407. for (var name in this._textures) {
  55408. if (this._textures[name] === texture) {
  55409. return true;
  55410. }
  55411. }
  55412. for (var name in this._textureArrays) {
  55413. var array = this._textureArrays[name];
  55414. for (var index = 0; index < array.length; index++) {
  55415. if (array[index] === texture) {
  55416. return true;
  55417. }
  55418. }
  55419. }
  55420. return false;
  55421. };
  55422. ShaderMaterial.prototype.clone = function (name) {
  55423. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55424. return newShaderMaterial;
  55425. };
  55426. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55427. if (forceDisposeTextures) {
  55428. var name;
  55429. for (name in this._textures) {
  55430. this._textures[name].dispose();
  55431. }
  55432. for (name in this._textureArrays) {
  55433. var array = this._textureArrays[name];
  55434. for (var index = 0; index < array.length; index++) {
  55435. array[index].dispose();
  55436. }
  55437. }
  55438. }
  55439. this._textures = {};
  55440. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55441. };
  55442. ShaderMaterial.prototype.serialize = function () {
  55443. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55444. serializationObject.customType = "BABYLON.ShaderMaterial";
  55445. serializationObject.options = this._options;
  55446. serializationObject.shaderPath = this._shaderPath;
  55447. var name;
  55448. // Texture
  55449. serializationObject.textures = {};
  55450. for (name in this._textures) {
  55451. serializationObject.textures[name] = this._textures[name].serialize();
  55452. }
  55453. // Texture arrays
  55454. serializationObject.textureArrays = {};
  55455. for (name in this._textureArrays) {
  55456. serializationObject.textureArrays[name] = [];
  55457. var array = this._textureArrays[name];
  55458. for (var index = 0; index < array.length; index++) {
  55459. serializationObject.textureArrays[name].push(array[index].serialize());
  55460. }
  55461. }
  55462. // Float
  55463. serializationObject.floats = {};
  55464. for (name in this._floats) {
  55465. serializationObject.floats[name] = this._floats[name];
  55466. }
  55467. // Float s
  55468. serializationObject.FloatArrays = {};
  55469. for (name in this._floatsArrays) {
  55470. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55471. }
  55472. // Color3
  55473. serializationObject.colors3 = {};
  55474. for (name in this._colors3) {
  55475. serializationObject.colors3[name] = this._colors3[name].asArray();
  55476. }
  55477. // Color3 array
  55478. serializationObject.colors3Arrays = {};
  55479. for (name in this._colors3Arrays) {
  55480. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55481. }
  55482. // Color4
  55483. serializationObject.colors4 = {};
  55484. for (name in this._colors4) {
  55485. serializationObject.colors4[name] = this._colors4[name].asArray();
  55486. }
  55487. // Vector2
  55488. serializationObject.vectors2 = {};
  55489. for (name in this._vectors2) {
  55490. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55491. }
  55492. // Vector3
  55493. serializationObject.vectors3 = {};
  55494. for (name in this._vectors3) {
  55495. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55496. }
  55497. // Vector4
  55498. serializationObject.vectors4 = {};
  55499. for (name in this._vectors4) {
  55500. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55501. }
  55502. // Matrix
  55503. serializationObject.matrices = {};
  55504. for (name in this._matrices) {
  55505. serializationObject.matrices[name] = this._matrices[name].asArray();
  55506. }
  55507. // Matrix 3x3
  55508. serializationObject.matrices3x3 = {};
  55509. for (name in this._matrices3x3) {
  55510. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55511. }
  55512. // Matrix 2x2
  55513. serializationObject.matrices2x2 = {};
  55514. for (name in this._matrices2x2) {
  55515. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55516. }
  55517. // Vector2Array
  55518. serializationObject.vectors2Arrays = {};
  55519. for (name in this._vectors2Arrays) {
  55520. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55521. }
  55522. // Vector3Array
  55523. serializationObject.vectors3Arrays = {};
  55524. for (name in this._vectors3Arrays) {
  55525. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55526. }
  55527. return serializationObject;
  55528. };
  55529. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55530. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55531. var name;
  55532. // Texture
  55533. for (name in source.textures) {
  55534. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55535. }
  55536. // Texture arrays
  55537. for (name in source.textureArrays) {
  55538. var array = source.textureArrays[name];
  55539. var textureArray = new Array();
  55540. for (var index = 0; index < array.length; index++) {
  55541. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55542. }
  55543. material.setTextureArray(name, textureArray);
  55544. }
  55545. // Float
  55546. for (name in source.floats) {
  55547. material.setFloat(name, source.floats[name]);
  55548. }
  55549. // Float s
  55550. for (name in source.floatsArrays) {
  55551. material.setFloats(name, source.floatsArrays[name]);
  55552. }
  55553. // Color3
  55554. for (name in source.colors3) {
  55555. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55556. }
  55557. // Color3 arrays
  55558. for (name in source.colors3Arrays) {
  55559. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55560. if (i % 3 === 0) {
  55561. arr.push([num]);
  55562. }
  55563. else {
  55564. arr[arr.length - 1].push(num);
  55565. }
  55566. return arr;
  55567. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55568. material.setColor3Array(name, colors);
  55569. }
  55570. // Color4
  55571. for (name in source.colors4) {
  55572. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55573. }
  55574. // Vector2
  55575. for (name in source.vectors2) {
  55576. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55577. }
  55578. // Vector3
  55579. for (name in source.vectors3) {
  55580. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55581. }
  55582. // Vector4
  55583. for (name in source.vectors4) {
  55584. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55585. }
  55586. // Matrix
  55587. for (name in source.matrices) {
  55588. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55589. }
  55590. // Matrix 3x3
  55591. for (name in source.matrices3x3) {
  55592. material.setMatrix3x3(name, source.matrices3x3[name]);
  55593. }
  55594. // Matrix 2x2
  55595. for (name in source.matrices2x2) {
  55596. material.setMatrix2x2(name, source.matrices2x2[name]);
  55597. }
  55598. // Vector2Array
  55599. for (name in source.vectors2Arrays) {
  55600. material.setArray2(name, source.vectors2Arrays[name]);
  55601. }
  55602. // Vector3Array
  55603. for (name in source.vectors3Arrays) {
  55604. material.setArray3(name, source.vectors3Arrays[name]);
  55605. }
  55606. return material;
  55607. };
  55608. return ShaderMaterial;
  55609. }(BABYLON.Material));
  55610. BABYLON.ShaderMaterial = ShaderMaterial;
  55611. })(BABYLON || (BABYLON = {}));
  55612. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55613. "use strict";
  55614. var BABYLON;
  55615. (function (BABYLON) {
  55616. var GroundMesh = /** @class */ (function (_super) {
  55617. __extends(GroundMesh, _super);
  55618. function GroundMesh(name, scene) {
  55619. var _this = _super.call(this, name, scene) || this;
  55620. _this.generateOctree = false;
  55621. return _this;
  55622. }
  55623. GroundMesh.prototype.getClassName = function () {
  55624. return "GroundMesh";
  55625. };
  55626. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55627. get: function () {
  55628. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55629. },
  55630. enumerable: true,
  55631. configurable: true
  55632. });
  55633. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55634. get: function () {
  55635. return this._subdivisionsX;
  55636. },
  55637. enumerable: true,
  55638. configurable: true
  55639. });
  55640. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55641. get: function () {
  55642. return this._subdivisionsY;
  55643. },
  55644. enumerable: true,
  55645. configurable: true
  55646. });
  55647. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55648. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55649. this._subdivisionsX = chunksCount;
  55650. this._subdivisionsY = chunksCount;
  55651. this.subdivide(chunksCount);
  55652. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55653. };
  55654. /**
  55655. * Returns a height (y) value in the Worl system :
  55656. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55657. * Returns the ground y position if (x, z) are outside the ground surface.
  55658. */
  55659. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55660. var world = this.getWorldMatrix();
  55661. var invMat = BABYLON.Tmp.Matrix[5];
  55662. world.invertToRef(invMat);
  55663. var tmpVect = BABYLON.Tmp.Vector3[8];
  55664. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55665. x = tmpVect.x;
  55666. z = tmpVect.z;
  55667. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55668. return this.position.y;
  55669. }
  55670. if (!this._heightQuads || this._heightQuads.length == 0) {
  55671. this._initHeightQuads();
  55672. this._computeHeightQuads();
  55673. }
  55674. var facet = this._getFacetAt(x, z);
  55675. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55676. // return y in the World system
  55677. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55678. return tmpVect.y;
  55679. };
  55680. /**
  55681. * Returns a normalized vector (Vector3) orthogonal to the ground
  55682. * at the ground coordinates (x, z) expressed in the World system.
  55683. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55684. */
  55685. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55686. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55687. this.getNormalAtCoordinatesToRef(x, z, normal);
  55688. return normal;
  55689. };
  55690. /**
  55691. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55692. * at the ground coordinates (x, z) expressed in the World system.
  55693. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55694. * Returns the GroundMesh.
  55695. */
  55696. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55697. var world = this.getWorldMatrix();
  55698. var tmpMat = BABYLON.Tmp.Matrix[5];
  55699. world.invertToRef(tmpMat);
  55700. var tmpVect = BABYLON.Tmp.Vector3[8];
  55701. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55702. x = tmpVect.x;
  55703. z = tmpVect.z;
  55704. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55705. return this;
  55706. }
  55707. if (!this._heightQuads || this._heightQuads.length == 0) {
  55708. this._initHeightQuads();
  55709. this._computeHeightQuads();
  55710. }
  55711. var facet = this._getFacetAt(x, z);
  55712. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55713. return this;
  55714. };
  55715. /**
  55716. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55717. * if the ground has been updated.
  55718. * This can be used in the render loop.
  55719. * Returns the GroundMesh.
  55720. */
  55721. GroundMesh.prototype.updateCoordinateHeights = function () {
  55722. if (!this._heightQuads || this._heightQuads.length == 0) {
  55723. this._initHeightQuads();
  55724. }
  55725. this._computeHeightQuads();
  55726. return this;
  55727. };
  55728. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55729. GroundMesh.prototype._getFacetAt = function (x, z) {
  55730. // retrieve col and row from x, z coordinates in the ground local system
  55731. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55732. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55733. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55734. var facet;
  55735. if (z < quad.slope.x * x + quad.slope.y) {
  55736. facet = quad.facet1;
  55737. }
  55738. else {
  55739. facet = quad.facet2;
  55740. }
  55741. return facet;
  55742. };
  55743. // Creates and populates the heightMap array with "facet" elements :
  55744. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55745. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55746. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55747. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55748. // Returns the GroundMesh.
  55749. GroundMesh.prototype._initHeightQuads = function () {
  55750. var subdivisionsX = this._subdivisionsX;
  55751. var subdivisionsY = this._subdivisionsY;
  55752. this._heightQuads = new Array();
  55753. for (var row = 0; row < subdivisionsY; row++) {
  55754. for (var col = 0; col < subdivisionsX; col++) {
  55755. 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) };
  55756. this._heightQuads[row * subdivisionsX + col] = quad;
  55757. }
  55758. }
  55759. return this;
  55760. };
  55761. // Compute each quad element values and update the the heightMap array :
  55762. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55763. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55764. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55765. // Returns the GroundMesh.
  55766. GroundMesh.prototype._computeHeightQuads = function () {
  55767. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55768. if (!positions) {
  55769. return this;
  55770. }
  55771. var v1 = BABYLON.Tmp.Vector3[3];
  55772. var v2 = BABYLON.Tmp.Vector3[2];
  55773. var v3 = BABYLON.Tmp.Vector3[1];
  55774. var v4 = BABYLON.Tmp.Vector3[0];
  55775. var v1v2 = BABYLON.Tmp.Vector3[4];
  55776. var v1v3 = BABYLON.Tmp.Vector3[5];
  55777. var v1v4 = BABYLON.Tmp.Vector3[6];
  55778. var norm1 = BABYLON.Tmp.Vector3[7];
  55779. var norm2 = BABYLON.Tmp.Vector3[8];
  55780. var i = 0;
  55781. var j = 0;
  55782. var k = 0;
  55783. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55784. var h = 0;
  55785. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55786. var d2 = 0;
  55787. var subdivisionsX = this._subdivisionsX;
  55788. var subdivisionsY = this._subdivisionsY;
  55789. for (var row = 0; row < subdivisionsY; row++) {
  55790. for (var col = 0; col < subdivisionsX; col++) {
  55791. i = col * 3;
  55792. j = row * (subdivisionsX + 1) * 3;
  55793. k = (row + 1) * (subdivisionsX + 1) * 3;
  55794. v1.x = positions[j + i];
  55795. v1.y = positions[j + i + 1];
  55796. v1.z = positions[j + i + 2];
  55797. v2.x = positions[j + i + 3];
  55798. v2.y = positions[j + i + 4];
  55799. v2.z = positions[j + i + 5];
  55800. v3.x = positions[k + i];
  55801. v3.y = positions[k + i + 1];
  55802. v3.z = positions[k + i + 2];
  55803. v4.x = positions[k + i + 3];
  55804. v4.y = positions[k + i + 4];
  55805. v4.z = positions[k + i + 5];
  55806. // 2D slope V1V4
  55807. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55808. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55809. // facet equations :
  55810. // we compute each facet normal vector
  55811. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55812. // we compute the value d by applying the equation to v1 which belongs to the plane
  55813. // then we store the facet equation in a Vector4
  55814. v2.subtractToRef(v1, v1v2);
  55815. v3.subtractToRef(v1, v1v3);
  55816. v4.subtractToRef(v1, v1v4);
  55817. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55818. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55819. norm1.normalize();
  55820. norm2.normalize();
  55821. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55822. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55823. var quad = this._heightQuads[row * subdivisionsX + col];
  55824. quad.slope.copyFromFloats(cd, h);
  55825. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55826. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55827. }
  55828. }
  55829. return this;
  55830. };
  55831. GroundMesh.prototype.serialize = function (serializationObject) {
  55832. _super.prototype.serialize.call(this, serializationObject);
  55833. serializationObject.subdivisionsX = this._subdivisionsX;
  55834. serializationObject.subdivisionsY = this._subdivisionsY;
  55835. serializationObject.minX = this._minX;
  55836. serializationObject.maxX = this._maxX;
  55837. serializationObject.minZ = this._minZ;
  55838. serializationObject.maxZ = this._maxZ;
  55839. serializationObject.width = this._width;
  55840. serializationObject.height = this._height;
  55841. };
  55842. GroundMesh.Parse = function (parsedMesh, scene) {
  55843. var result = new GroundMesh(parsedMesh.name, scene);
  55844. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55845. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55846. result._minX = parsedMesh.minX;
  55847. result._maxX = parsedMesh.maxX;
  55848. result._minZ = parsedMesh.minZ;
  55849. result._maxZ = parsedMesh.maxZ;
  55850. result._width = parsedMesh.width;
  55851. result._height = parsedMesh.height;
  55852. return result;
  55853. };
  55854. return GroundMesh;
  55855. }(BABYLON.Mesh));
  55856. BABYLON.GroundMesh = GroundMesh;
  55857. })(BABYLON || (BABYLON = {}));
  55858. //# sourceMappingURL=babylon.groundMesh.js.map
  55859. "use strict";
  55860. var BABYLON;
  55861. (function (BABYLON) {
  55862. /**
  55863. * Creates an instance based on a source mesh.
  55864. */
  55865. var InstancedMesh = /** @class */ (function (_super) {
  55866. __extends(InstancedMesh, _super);
  55867. function InstancedMesh(name, source) {
  55868. var _this = _super.call(this, name, source.getScene()) || this;
  55869. source.instances.push(_this);
  55870. _this._sourceMesh = source;
  55871. _this.position.copyFrom(source.position);
  55872. _this.rotation.copyFrom(source.rotation);
  55873. _this.scaling.copyFrom(source.scaling);
  55874. if (source.rotationQuaternion) {
  55875. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55876. }
  55877. _this.infiniteDistance = source.infiniteDistance;
  55878. _this.setPivotMatrix(source.getPivotMatrix());
  55879. _this.refreshBoundingInfo();
  55880. _this._syncSubMeshes();
  55881. return _this;
  55882. }
  55883. /**
  55884. * Returns the string "InstancedMesh".
  55885. */
  55886. InstancedMesh.prototype.getClassName = function () {
  55887. return "InstancedMesh";
  55888. };
  55889. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55890. // Methods
  55891. get: function () {
  55892. return this._sourceMesh.receiveShadows;
  55893. },
  55894. enumerable: true,
  55895. configurable: true
  55896. });
  55897. Object.defineProperty(InstancedMesh.prototype, "material", {
  55898. get: function () {
  55899. return this._sourceMesh.material;
  55900. },
  55901. enumerable: true,
  55902. configurable: true
  55903. });
  55904. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55905. get: function () {
  55906. return this._sourceMesh.visibility;
  55907. },
  55908. enumerable: true,
  55909. configurable: true
  55910. });
  55911. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55912. get: function () {
  55913. return this._sourceMesh.skeleton;
  55914. },
  55915. enumerable: true,
  55916. configurable: true
  55917. });
  55918. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55919. get: function () {
  55920. return this._sourceMesh.renderingGroupId;
  55921. },
  55922. set: function (value) {
  55923. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55924. return;
  55925. }
  55926. //no-op with warning
  55927. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55928. },
  55929. enumerable: true,
  55930. configurable: true
  55931. });
  55932. /**
  55933. * Returns the total number of vertices (integer).
  55934. */
  55935. InstancedMesh.prototype.getTotalVertices = function () {
  55936. return this._sourceMesh.getTotalVertices();
  55937. };
  55938. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55939. get: function () {
  55940. return this._sourceMesh;
  55941. },
  55942. enumerable: true,
  55943. configurable: true
  55944. });
  55945. /**
  55946. * Is this node ready to be used/rendered
  55947. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55948. * @return {boolean} is it ready
  55949. */
  55950. InstancedMesh.prototype.isReady = function (completeCheck) {
  55951. if (completeCheck === void 0) { completeCheck = false; }
  55952. return this._sourceMesh.isReady(completeCheck, true);
  55953. };
  55954. /**
  55955. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55956. */
  55957. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55958. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55959. };
  55960. /**
  55961. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55962. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55963. * The `data` are either a numeric array either a Float32Array.
  55964. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55965. * 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).
  55966. * Note that a new underlying VertexBuffer object is created each call.
  55967. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55968. *
  55969. * Possible `kind` values :
  55970. * - BABYLON.VertexBuffer.PositionKind
  55971. * - BABYLON.VertexBuffer.UVKind
  55972. * - BABYLON.VertexBuffer.UV2Kind
  55973. * - BABYLON.VertexBuffer.UV3Kind
  55974. * - BABYLON.VertexBuffer.UV4Kind
  55975. * - BABYLON.VertexBuffer.UV5Kind
  55976. * - BABYLON.VertexBuffer.UV6Kind
  55977. * - BABYLON.VertexBuffer.ColorKind
  55978. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55979. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55980. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55981. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55982. *
  55983. * Returns the Mesh.
  55984. */
  55985. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55986. if (this.sourceMesh) {
  55987. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55988. }
  55989. return this.sourceMesh;
  55990. };
  55991. /**
  55992. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55993. * If the mesh has no geometry, it is simply returned as it is.
  55994. * The `data` are either a numeric array either a Float32Array.
  55995. * No new underlying VertexBuffer object is created.
  55996. * 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.
  55997. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55998. *
  55999. * Possible `kind` values :
  56000. * - BABYLON.VertexBuffer.PositionKind
  56001. * - BABYLON.VertexBuffer.UVKind
  56002. * - BABYLON.VertexBuffer.UV2Kind
  56003. * - BABYLON.VertexBuffer.UV3Kind
  56004. * - BABYLON.VertexBuffer.UV4Kind
  56005. * - BABYLON.VertexBuffer.UV5Kind
  56006. * - BABYLON.VertexBuffer.UV6Kind
  56007. * - BABYLON.VertexBuffer.ColorKind
  56008. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56009. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56010. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56011. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56012. *
  56013. * Returns the Mesh.
  56014. */
  56015. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56016. if (this.sourceMesh) {
  56017. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56018. }
  56019. return this.sourceMesh;
  56020. };
  56021. /**
  56022. * Sets the mesh indices.
  56023. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56024. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56025. * This method creates a new index buffer each call.
  56026. * Returns the Mesh.
  56027. */
  56028. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56029. if (totalVertices === void 0) { totalVertices = null; }
  56030. if (this.sourceMesh) {
  56031. this.sourceMesh.setIndices(indices, totalVertices);
  56032. }
  56033. return this.sourceMesh;
  56034. };
  56035. /**
  56036. * Boolean : True if the mesh owns the requested kind of data.
  56037. */
  56038. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56039. return this._sourceMesh.isVerticesDataPresent(kind);
  56040. };
  56041. /**
  56042. * Returns an array of indices (IndicesArray).
  56043. */
  56044. InstancedMesh.prototype.getIndices = function () {
  56045. return this._sourceMesh.getIndices();
  56046. };
  56047. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56048. get: function () {
  56049. return this._sourceMesh._positions;
  56050. },
  56051. enumerable: true,
  56052. configurable: true
  56053. });
  56054. /**
  56055. * Sets a new updated BoundingInfo to the mesh.
  56056. * Returns the mesh.
  56057. */
  56058. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56059. var meshBB = this._sourceMesh.getBoundingInfo();
  56060. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56061. this._updateBoundingInfo();
  56062. return this;
  56063. };
  56064. InstancedMesh.prototype._preActivate = function () {
  56065. if (this._currentLOD) {
  56066. this._currentLOD._preActivate();
  56067. }
  56068. return this;
  56069. };
  56070. InstancedMesh.prototype._activate = function (renderId) {
  56071. if (this._currentLOD) {
  56072. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56073. }
  56074. return this;
  56075. };
  56076. /**
  56077. * Returns the current associated LOD AbstractMesh.
  56078. */
  56079. InstancedMesh.prototype.getLOD = function (camera) {
  56080. if (!camera) {
  56081. return this;
  56082. }
  56083. var boundingInfo = this.getBoundingInfo();
  56084. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56085. if (this._currentLOD === this.sourceMesh) {
  56086. return this;
  56087. }
  56088. return this._currentLOD;
  56089. };
  56090. InstancedMesh.prototype._syncSubMeshes = function () {
  56091. this.releaseSubMeshes();
  56092. if (this._sourceMesh.subMeshes) {
  56093. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56094. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56095. }
  56096. }
  56097. return this;
  56098. };
  56099. InstancedMesh.prototype._generatePointsArray = function () {
  56100. return this._sourceMesh._generatePointsArray();
  56101. };
  56102. /**
  56103. * Creates a new InstancedMesh from the current mesh.
  56104. * - name (string) : the cloned mesh name
  56105. * - newParent (optional Node) : the optional Node to parent the clone to.
  56106. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56107. *
  56108. * Returns the clone.
  56109. */
  56110. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56111. var result = this._sourceMesh.createInstance(name);
  56112. // Deep copy
  56113. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56114. // Bounding info
  56115. this.refreshBoundingInfo();
  56116. // Parent
  56117. if (newParent) {
  56118. result.parent = newParent;
  56119. }
  56120. if (!doNotCloneChildren) {
  56121. // Children
  56122. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56123. var mesh = this.getScene().meshes[index];
  56124. if (mesh.parent === this) {
  56125. mesh.clone(mesh.name, result);
  56126. }
  56127. }
  56128. }
  56129. result.computeWorldMatrix(true);
  56130. return result;
  56131. };
  56132. /**
  56133. * Disposes the InstancedMesh.
  56134. * Returns nothing.
  56135. */
  56136. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56137. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56138. // Remove from mesh
  56139. var index = this._sourceMesh.instances.indexOf(this);
  56140. this._sourceMesh.instances.splice(index, 1);
  56141. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56142. };
  56143. return InstancedMesh;
  56144. }(BABYLON.AbstractMesh));
  56145. BABYLON.InstancedMesh = InstancedMesh;
  56146. })(BABYLON || (BABYLON = {}));
  56147. //# sourceMappingURL=babylon.instancedMesh.js.map
  56148. "use strict";
  56149. var BABYLON;
  56150. (function (BABYLON) {
  56151. var LinesMesh = /** @class */ (function (_super) {
  56152. __extends(LinesMesh, _super);
  56153. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56154. if (scene === void 0) { scene = null; }
  56155. if (parent === void 0) { parent = null; }
  56156. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56157. _this.useVertexColor = useVertexColor;
  56158. _this.useVertexAlpha = useVertexAlpha;
  56159. _this.color = new BABYLON.Color3(1, 1, 1);
  56160. _this.alpha = 1;
  56161. if (source) {
  56162. _this.color = source.color.clone();
  56163. _this.alpha = source.alpha;
  56164. _this.useVertexColor = source.useVertexColor;
  56165. _this.useVertexAlpha = source.useVertexAlpha;
  56166. }
  56167. _this._intersectionThreshold = 0.1;
  56168. var defines = [];
  56169. var options = {
  56170. attributes: [BABYLON.VertexBuffer.PositionKind],
  56171. uniforms: ["world", "viewProjection"],
  56172. needAlphaBlending: true,
  56173. defines: defines
  56174. };
  56175. if (useVertexAlpha === false) {
  56176. options.needAlphaBlending = false;
  56177. }
  56178. if (!useVertexColor) {
  56179. options.uniforms.push("color");
  56180. }
  56181. else {
  56182. options.defines.push("#define VERTEXCOLOR");
  56183. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56184. }
  56185. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56186. return _this;
  56187. }
  56188. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56189. /**
  56190. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56191. * This margin is expressed in world space coordinates, so its value may vary.
  56192. * Default value is 0.1
  56193. * @returns the intersection Threshold value.
  56194. */
  56195. get: function () {
  56196. return this._intersectionThreshold;
  56197. },
  56198. /**
  56199. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56200. * This margin is expressed in world space coordinates, so its value may vary.
  56201. * @param value the new threshold to apply
  56202. */
  56203. set: function (value) {
  56204. if (this._intersectionThreshold === value) {
  56205. return;
  56206. }
  56207. this._intersectionThreshold = value;
  56208. if (this.geometry) {
  56209. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56210. }
  56211. },
  56212. enumerable: true,
  56213. configurable: true
  56214. });
  56215. /**
  56216. * Returns the string "LineMesh"
  56217. */
  56218. LinesMesh.prototype.getClassName = function () {
  56219. return "LinesMesh";
  56220. };
  56221. Object.defineProperty(LinesMesh.prototype, "material", {
  56222. get: function () {
  56223. return this._colorShader;
  56224. },
  56225. set: function (value) {
  56226. // Do nothing
  56227. },
  56228. enumerable: true,
  56229. configurable: true
  56230. });
  56231. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56232. get: function () {
  56233. return false;
  56234. },
  56235. enumerable: true,
  56236. configurable: true
  56237. });
  56238. LinesMesh.prototype.createInstance = function (name) {
  56239. throw new Error("LinesMeshes do not support createInstance.");
  56240. };
  56241. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56242. if (!this._geometry) {
  56243. return this;
  56244. }
  56245. // VBOs
  56246. this._geometry._bind(this._colorShader.getEffect());
  56247. // Color
  56248. if (!this.useVertexColor) {
  56249. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56250. }
  56251. return this;
  56252. };
  56253. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56254. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56255. return this;
  56256. }
  56257. var engine = this.getScene().getEngine();
  56258. // Draw order
  56259. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56260. return this;
  56261. };
  56262. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56263. this._colorShader.dispose();
  56264. _super.prototype.dispose.call(this, doNotRecurse);
  56265. };
  56266. /**
  56267. * Returns a new LineMesh object cloned from the current one.
  56268. */
  56269. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56270. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56271. };
  56272. return LinesMesh;
  56273. }(BABYLON.Mesh));
  56274. BABYLON.LinesMesh = LinesMesh;
  56275. })(BABYLON || (BABYLON = {}));
  56276. //# sourceMappingURL=babylon.linesMesh.js.map
  56277. "use strict";
  56278. var BABYLON;
  56279. (function (BABYLON) {
  56280. var MeshBuilder = /** @class */ (function () {
  56281. function MeshBuilder() {
  56282. }
  56283. MeshBuilder.updateSideOrientation = function (orientation) {
  56284. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56285. return BABYLON.Mesh.DOUBLESIDE;
  56286. }
  56287. if (orientation === undefined || orientation === null) {
  56288. return BABYLON.Mesh.FRONTSIDE;
  56289. }
  56290. return orientation;
  56291. };
  56292. /**
  56293. * Creates a box mesh.
  56294. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56295. * The parameter `size` sets the size (float) of each box side (default 1).
  56296. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56297. * 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).
  56298. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56299. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56300. * 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).
  56301. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56303. */
  56304. MeshBuilder.CreateBox = function (name, options, scene) {
  56305. if (scene === void 0) { scene = null; }
  56306. var box = new BABYLON.Mesh(name, scene);
  56307. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56308. box._originalBuilderSideOrientation = options.sideOrientation;
  56309. var vertexData = BABYLON.VertexData.CreateBox(options);
  56310. vertexData.applyToMesh(box, options.updatable);
  56311. return box;
  56312. };
  56313. /**
  56314. * Creates a sphere mesh.
  56315. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56316. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56317. * 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`).
  56318. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56319. * 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
  56320. * 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).
  56321. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56322. * 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).
  56323. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56324. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56325. */
  56326. MeshBuilder.CreateSphere = function (name, options, scene) {
  56327. var sphere = new BABYLON.Mesh(name, scene);
  56328. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56329. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56330. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56331. vertexData.applyToMesh(sphere, options.updatable);
  56332. return sphere;
  56333. };
  56334. /**
  56335. * Creates a plane polygonal mesh. By default, this is a disc.
  56336. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56337. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56338. * 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.
  56339. * 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
  56340. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56341. * 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).
  56342. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56344. */
  56345. MeshBuilder.CreateDisc = function (name, options, scene) {
  56346. if (scene === void 0) { scene = null; }
  56347. var disc = new BABYLON.Mesh(name, scene);
  56348. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56349. disc._originalBuilderSideOrientation = options.sideOrientation;
  56350. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56351. vertexData.applyToMesh(disc, options.updatable);
  56352. return disc;
  56353. };
  56354. /**
  56355. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56356. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56357. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56358. * 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`).
  56359. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56360. * 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.
  56361. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56362. * 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).
  56363. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56365. */
  56366. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56367. var sphere = new BABYLON.Mesh(name, scene);
  56368. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56369. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56370. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56371. vertexData.applyToMesh(sphere, options.updatable);
  56372. return sphere;
  56373. };
  56374. ;
  56375. /**
  56376. * Creates a ribbon mesh.
  56377. * 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.
  56378. *
  56379. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56380. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56381. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56382. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56383. * 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.
  56384. * 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.
  56385. * 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
  56386. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56387. * 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).
  56388. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56389. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56390. * 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.
  56391. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56392. * 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
  56393. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56394. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56395. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56396. */
  56397. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56398. if (scene === void 0) { scene = null; }
  56399. var pathArray = options.pathArray;
  56400. var closeArray = options.closeArray;
  56401. var closePath = options.closePath;
  56402. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56403. var instance = options.instance;
  56404. var updatable = options.updatable;
  56405. if (instance) {
  56406. // positionFunction : ribbon case
  56407. // only pathArray and sideOrientation parameters are taken into account for positions update
  56408. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56409. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56410. var positionFunction = function (positions) {
  56411. var minlg = pathArray[0].length;
  56412. var i = 0;
  56413. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56414. for (var si = 1; si <= ns; si++) {
  56415. for (var p = 0; p < pathArray.length; p++) {
  56416. var path = pathArray[p];
  56417. var l = path.length;
  56418. minlg = (minlg < l) ? minlg : l;
  56419. var j = 0;
  56420. while (j < minlg) {
  56421. positions[i] = path[j].x;
  56422. positions[i + 1] = path[j].y;
  56423. positions[i + 2] = path[j].z;
  56424. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56425. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56426. }
  56427. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56428. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56429. }
  56430. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56431. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56432. }
  56433. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56434. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56435. }
  56436. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56437. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56438. }
  56439. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56440. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56441. }
  56442. j++;
  56443. i += 3;
  56444. }
  56445. if (instance._closePath) {
  56446. positions[i] = path[0].x;
  56447. positions[i + 1] = path[0].y;
  56448. positions[i + 2] = path[0].z;
  56449. i += 3;
  56450. }
  56451. }
  56452. }
  56453. };
  56454. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56455. positionFunction(positions);
  56456. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56457. instance._boundingInfo.update(instance._worldMatrix);
  56458. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56459. if (options.colors) {
  56460. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56461. for (var c = 0; c < options.colors.length; c++) {
  56462. colors[c * 4] = options.colors[c].r;
  56463. colors[c * 4 + 1] = options.colors[c].g;
  56464. colors[c * 4 + 2] = options.colors[c].b;
  56465. colors[c * 4 + 3] = options.colors[c].a;
  56466. }
  56467. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56468. }
  56469. if (options.uvs) {
  56470. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56471. for (var i = 0; i < options.uvs.length; i++) {
  56472. uvs[i * 2] = options.uvs[i].x;
  56473. uvs[i * 2 + 1] = options.uvs[i].y;
  56474. }
  56475. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56476. }
  56477. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56478. var indices = instance.getIndices();
  56479. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56480. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56481. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56482. if (instance._closePath) {
  56483. var indexFirst = 0;
  56484. var indexLast = 0;
  56485. for (var p = 0; p < pathArray.length; p++) {
  56486. indexFirst = instance._idx[p] * 3;
  56487. if (p + 1 < pathArray.length) {
  56488. indexLast = (instance._idx[p + 1] - 1) * 3;
  56489. }
  56490. else {
  56491. indexLast = normals.length - 3;
  56492. }
  56493. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56494. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56495. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56496. normals[indexLast] = normals[indexFirst];
  56497. normals[indexLast + 1] = normals[indexFirst + 1];
  56498. normals[indexLast + 2] = normals[indexFirst + 2];
  56499. }
  56500. }
  56501. if (!(instance.areNormalsFrozen)) {
  56502. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56503. }
  56504. }
  56505. return instance;
  56506. }
  56507. else {
  56508. var ribbon = new BABYLON.Mesh(name, scene);
  56509. ribbon._originalBuilderSideOrientation = sideOrientation;
  56510. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56511. if (closePath) {
  56512. ribbon._idx = vertexData._idx;
  56513. }
  56514. ribbon._closePath = closePath;
  56515. ribbon._closeArray = closeArray;
  56516. vertexData.applyToMesh(ribbon, updatable);
  56517. return ribbon;
  56518. }
  56519. };
  56520. /**
  56521. * Creates a cylinder or a cone mesh.
  56522. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56523. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56524. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56525. * 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.
  56526. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56527. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56528. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56529. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56530. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56531. * 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).
  56532. * 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
  56533. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56534. * 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
  56535. * 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.
  56536. * If `enclose` is false, a ring surface is one element.
  56537. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56538. * 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
  56539. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56540. * 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).
  56541. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56542. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56543. */
  56544. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56545. var cylinder = new BABYLON.Mesh(name, scene);
  56546. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56547. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56548. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56549. vertexData.applyToMesh(cylinder, options.updatable);
  56550. return cylinder;
  56551. };
  56552. /**
  56553. * Creates a torus mesh.
  56554. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56555. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56556. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56557. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56558. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56559. * 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).
  56560. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56562. */
  56563. MeshBuilder.CreateTorus = function (name, options, scene) {
  56564. var torus = new BABYLON.Mesh(name, scene);
  56565. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56566. torus._originalBuilderSideOrientation = options.sideOrientation;
  56567. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56568. vertexData.applyToMesh(torus, options.updatable);
  56569. return torus;
  56570. };
  56571. /**
  56572. * Creates a torus knot mesh.
  56573. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56574. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56575. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56576. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56577. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56578. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56579. * 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).
  56580. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56582. */
  56583. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56584. var torusKnot = new BABYLON.Mesh(name, scene);
  56585. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56586. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56587. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56588. vertexData.applyToMesh(torusKnot, options.updatable);
  56589. return torusKnot;
  56590. };
  56591. /**
  56592. * Creates a line system mesh.
  56593. * A line system is a pool of many lines gathered in a single mesh.
  56594. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56595. * 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.
  56596. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56597. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56598. * 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
  56599. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56600. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56601. * 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
  56602. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56603. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56604. */
  56605. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56606. var instance = options.instance;
  56607. var lines = options.lines;
  56608. var colors = options.colors;
  56609. if (instance) {
  56610. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56611. var vertexColor;
  56612. var lineColors;
  56613. if (colors) {
  56614. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56615. }
  56616. var i = 0;
  56617. var c = 0;
  56618. for (var l = 0; l < lines.length; l++) {
  56619. var points = lines[l];
  56620. for (var p = 0; p < points.length; p++) {
  56621. positions[i] = points[p].x;
  56622. positions[i + 1] = points[p].y;
  56623. positions[i + 2] = points[p].z;
  56624. if (colors && vertexColor) {
  56625. lineColors = colors[l];
  56626. vertexColor[c] = lineColors[p].r;
  56627. vertexColor[c + 1] = lineColors[p].g;
  56628. vertexColor[c + 2] = lineColors[p].b;
  56629. vertexColor[c + 3] = lineColors[p].a;
  56630. c += 4;
  56631. }
  56632. i += 3;
  56633. }
  56634. }
  56635. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56636. if (colors && vertexColor) {
  56637. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56638. }
  56639. return instance;
  56640. }
  56641. // line system creation
  56642. var useVertexColor = (colors) ? true : false;
  56643. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56644. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56645. vertexData.applyToMesh(lineSystem, options.updatable);
  56646. return lineSystem;
  56647. };
  56648. /**
  56649. * Creates a line mesh.
  56650. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56651. * 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.
  56652. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56653. * The parameter `points` is an array successive Vector3.
  56654. * 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
  56655. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56656. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56657. * When updating an instance, remember that only point positions can change, not the number of points.
  56658. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56659. */
  56660. MeshBuilder.CreateLines = function (name, options, scene) {
  56661. if (scene === void 0) { scene = null; }
  56662. var colors = (options.colors) ? [options.colors] : null;
  56663. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56664. return lines;
  56665. };
  56666. /**
  56667. * Creates a dashed line mesh.
  56668. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56669. * 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.
  56670. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56671. * The parameter `points` is an array successive Vector3.
  56672. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56673. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56674. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56675. * 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
  56676. * When updating an instance, remember that only point positions can change, not the number of points.
  56677. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56678. */
  56679. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56680. if (scene === void 0) { scene = null; }
  56681. var points = options.points;
  56682. var instance = options.instance;
  56683. var gapSize = options.gapSize || 1;
  56684. var dashSize = options.dashSize || 3;
  56685. if (instance) {
  56686. var positionFunction = function (positions) {
  56687. var curvect = BABYLON.Vector3.Zero();
  56688. var nbSeg = positions.length / 6;
  56689. var lg = 0;
  56690. var nb = 0;
  56691. var shft = 0;
  56692. var dashshft = 0;
  56693. var curshft = 0;
  56694. var p = 0;
  56695. var i = 0;
  56696. var j = 0;
  56697. for (i = 0; i < points.length - 1; i++) {
  56698. points[i + 1].subtractToRef(points[i], curvect);
  56699. lg += curvect.length();
  56700. }
  56701. shft = lg / nbSeg;
  56702. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56703. for (i = 0; i < points.length - 1; i++) {
  56704. points[i + 1].subtractToRef(points[i], curvect);
  56705. nb = Math.floor(curvect.length() / shft);
  56706. curvect.normalize();
  56707. j = 0;
  56708. while (j < nb && p < positions.length) {
  56709. curshft = shft * j;
  56710. positions[p] = points[i].x + curshft * curvect.x;
  56711. positions[p + 1] = points[i].y + curshft * curvect.y;
  56712. positions[p + 2] = points[i].z + curshft * curvect.z;
  56713. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56714. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56715. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56716. p += 6;
  56717. j++;
  56718. }
  56719. }
  56720. while (p < positions.length) {
  56721. positions[p] = points[i].x;
  56722. positions[p + 1] = points[i].y;
  56723. positions[p + 2] = points[i].z;
  56724. p += 3;
  56725. }
  56726. };
  56727. instance.updateMeshPositions(positionFunction, false);
  56728. return instance;
  56729. }
  56730. // dashed lines creation
  56731. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56732. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56733. vertexData.applyToMesh(dashedLines, options.updatable);
  56734. dashedLines.dashSize = dashSize;
  56735. dashedLines.gapSize = gapSize;
  56736. return dashedLines;
  56737. };
  56738. /**
  56739. * Creates an extruded shape mesh.
  56740. * 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.
  56741. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56742. *
  56743. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56744. * 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
  56745. * extruded along the Z axis.
  56746. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56747. * 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.
  56748. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56749. * 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
  56750. * 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
  56751. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56752. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56753. * 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).
  56754. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56755. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56757. */
  56758. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56759. if (scene === void 0) { scene = null; }
  56760. var path = options.path;
  56761. var shape = options.shape;
  56762. var scale = options.scale || 1;
  56763. var rotation = options.rotation || 0;
  56764. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56765. var updatable = options.updatable;
  56766. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56767. var instance = options.instance || null;
  56768. var invertUV = options.invertUV || false;
  56769. 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);
  56770. };
  56771. /**
  56772. * Creates an custom extruded shape mesh.
  56773. * 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.
  56774. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56775. *
  56776. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56777. * 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
  56778. * extruded along the Z axis.
  56779. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56780. * 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
  56781. * and the distance of this point from the begining of the path :
  56782. * ```javascript
  56783. * var rotationFunction = function(i, distance) {
  56784. * // do things
  56785. * return rotationValue; }
  56786. * ```
  56787. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56788. * 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
  56789. * and the distance of this point from the begining of the path :
  56790. * ```javascript
  56791. * var scaleFunction = function(i, distance) {
  56792. * // do things
  56793. * return scaleValue;}
  56794. * ```
  56795. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56796. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56797. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56798. * 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
  56799. * 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
  56800. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56801. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56802. * 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).
  56803. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56804. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56806. */
  56807. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56808. var path = options.path;
  56809. var shape = options.shape;
  56810. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56811. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56812. var ribbonCloseArray = options.ribbonCloseArray || false;
  56813. var ribbonClosePath = options.ribbonClosePath || false;
  56814. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56815. var updatable = options.updatable;
  56816. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56817. var instance = options.instance;
  56818. var invertUV = options.invertUV || false;
  56819. 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);
  56820. };
  56821. /**
  56822. * Creates lathe mesh.
  56823. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56824. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56825. *
  56826. * 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
  56827. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56828. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56829. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56830. * 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.
  56831. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56832. * 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
  56833. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56834. * 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).
  56835. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56836. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56837. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56838. */
  56839. MeshBuilder.CreateLathe = function (name, options, scene) {
  56840. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56841. var closed = (options.closed === undefined) ? true : options.closed;
  56842. var shape = options.shape;
  56843. var radius = options.radius || 1;
  56844. var tessellation = options.tessellation || 64;
  56845. var updatable = options.updatable;
  56846. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56847. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56848. var pi2 = Math.PI * 2;
  56849. var paths = new Array();
  56850. var invertUV = options.invertUV || false;
  56851. var i = 0;
  56852. var p = 0;
  56853. var step = pi2 / tessellation * arc;
  56854. var rotated;
  56855. var path = new Array();
  56856. ;
  56857. for (i = 0; i <= tessellation; i++) {
  56858. var path = [];
  56859. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56860. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56861. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56862. }
  56863. for (p = 0; p < shape.length; p++) {
  56864. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56865. path.push(rotated);
  56866. }
  56867. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56868. 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));
  56869. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56870. }
  56871. paths.push(path);
  56872. }
  56873. // lathe ribbon
  56874. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56875. return lathe;
  56876. };
  56877. /**
  56878. * Creates a plane mesh.
  56879. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56880. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56881. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56882. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56883. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56884. * 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).
  56885. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56887. */
  56888. MeshBuilder.CreatePlane = function (name, options, scene) {
  56889. var plane = new BABYLON.Mesh(name, scene);
  56890. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56891. plane._originalBuilderSideOrientation = options.sideOrientation;
  56892. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56893. vertexData.applyToMesh(plane, options.updatable);
  56894. if (options.sourcePlane) {
  56895. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56896. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56897. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56898. plane.rotate(vectorProduct, product);
  56899. }
  56900. return plane;
  56901. };
  56902. /**
  56903. * Creates a ground mesh.
  56904. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56905. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56906. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56908. */
  56909. MeshBuilder.CreateGround = function (name, options, scene) {
  56910. var ground = new BABYLON.GroundMesh(name, scene);
  56911. ground._setReady(false);
  56912. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56913. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56914. ground._width = options.width || 1;
  56915. ground._height = options.height || 1;
  56916. ground._maxX = ground._width / 2;
  56917. ground._maxZ = ground._height / 2;
  56918. ground._minX = -ground._maxX;
  56919. ground._minZ = -ground._maxZ;
  56920. var vertexData = BABYLON.VertexData.CreateGround(options);
  56921. vertexData.applyToMesh(ground, options.updatable);
  56922. ground._setReady(true);
  56923. return ground;
  56924. };
  56925. /**
  56926. * Creates a tiled ground mesh.
  56927. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56928. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56929. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56930. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56931. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56932. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56933. * numbers of subdivisions on the ground width and height of each tile.
  56934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56935. */
  56936. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56937. var tiledGround = new BABYLON.Mesh(name, scene);
  56938. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56939. vertexData.applyToMesh(tiledGround, options.updatable);
  56940. return tiledGround;
  56941. };
  56942. /**
  56943. * Creates a ground mesh from a height map.
  56944. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56945. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56946. * The parameter `url` sets the URL of the height map image resource.
  56947. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56948. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56949. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56950. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56951. * 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.
  56952. * 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).
  56953. * This function is passed the newly built mesh :
  56954. * ```javascript
  56955. * function(mesh) { // do things
  56956. * return; }
  56957. * ```
  56958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56959. */
  56960. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56961. var width = options.width || 10.0;
  56962. var height = options.height || 10.0;
  56963. var subdivisions = options.subdivisions || 1 | 0;
  56964. var minHeight = options.minHeight || 0.0;
  56965. var maxHeight = options.maxHeight || 1.0;
  56966. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56967. var updatable = options.updatable;
  56968. var onReady = options.onReady;
  56969. var ground = new BABYLON.GroundMesh(name, scene);
  56970. ground._subdivisionsX = subdivisions;
  56971. ground._subdivisionsY = subdivisions;
  56972. ground._width = width;
  56973. ground._height = height;
  56974. ground._maxX = ground._width / 2.0;
  56975. ground._maxZ = ground._height / 2.0;
  56976. ground._minX = -ground._maxX;
  56977. ground._minZ = -ground._maxZ;
  56978. ground._setReady(false);
  56979. var onload = function (img) {
  56980. // Getting height map data
  56981. var canvas = document.createElement("canvas");
  56982. var context = canvas.getContext("2d");
  56983. if (!context) {
  56984. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56985. }
  56986. if (scene.isDisposed) {
  56987. return;
  56988. }
  56989. var bufferWidth = img.width;
  56990. var bufferHeight = img.height;
  56991. canvas.width = bufferWidth;
  56992. canvas.height = bufferHeight;
  56993. context.drawImage(img, 0, 0);
  56994. // Create VertexData from map data
  56995. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56996. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56997. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56998. width: width, height: height,
  56999. subdivisions: subdivisions,
  57000. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57001. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57002. });
  57003. vertexData.applyToMesh(ground, updatable);
  57004. //execute ready callback, if set
  57005. if (onReady) {
  57006. onReady(ground);
  57007. }
  57008. ground._setReady(true);
  57009. };
  57010. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57011. return ground;
  57012. };
  57013. /**
  57014. * Creates a polygon mesh.
  57015. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57016. * 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.
  57017. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57018. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57019. * 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).
  57020. * Remember you can only change the shape positions, not their number when updating a polygon.
  57021. */
  57022. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57023. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57024. var shape = options.shape;
  57025. var holes = options.holes || [];
  57026. var depth = options.depth || 0;
  57027. var contours = [];
  57028. var hole = [];
  57029. for (var i = 0; i < shape.length; i++) {
  57030. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57031. }
  57032. var epsilon = 0.00000001;
  57033. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57034. contours.pop();
  57035. }
  57036. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57037. for (var hNb = 0; hNb < holes.length; hNb++) {
  57038. hole = [];
  57039. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57040. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57041. }
  57042. polygonTriangulation.addHole(hole);
  57043. }
  57044. var polygon = polygonTriangulation.build(options.updatable, depth);
  57045. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57046. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57047. vertexData.applyToMesh(polygon, options.updatable);
  57048. return polygon;
  57049. };
  57050. ;
  57051. /**
  57052. * Creates an extruded polygon mesh, with depth in the Y direction.
  57053. * 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).
  57054. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57055. */
  57056. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57057. return MeshBuilder.CreatePolygon(name, options, scene);
  57058. };
  57059. ;
  57060. /**
  57061. * Creates a tube mesh.
  57062. * 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.
  57063. *
  57064. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57065. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57066. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57067. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57068. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57069. * 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.
  57070. * It must return a radius value (positive float) :
  57071. * ```javascript
  57072. * var radiusFunction = function(i, distance) {
  57073. * // do things
  57074. * return radius; }
  57075. * ```
  57076. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57077. * 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
  57078. * 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
  57079. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57080. * 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).
  57081. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57082. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57083. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57084. */
  57085. MeshBuilder.CreateTube = function (name, options, scene) {
  57086. var path = options.path;
  57087. var instance = options.instance;
  57088. var radius = 1.0;
  57089. if (instance) {
  57090. radius = instance.radius;
  57091. }
  57092. if (options.radius !== undefined) {
  57093. radius = options.radius;
  57094. }
  57095. ;
  57096. var tessellation = options.tessellation || 64 | 0;
  57097. var radiusFunction = options.radiusFunction || null;
  57098. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57099. var invertUV = options.invertUV || false;
  57100. var updatable = options.updatable;
  57101. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57102. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57103. // tube geometry
  57104. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57105. var tangents = path3D.getTangents();
  57106. var normals = path3D.getNormals();
  57107. var distances = path3D.getDistances();
  57108. var pi2 = Math.PI * 2;
  57109. var step = pi2 / tessellation * arc;
  57110. var returnRadius = function () { return radius; };
  57111. var radiusFunctionFinal = radiusFunction || returnRadius;
  57112. var circlePath;
  57113. var rad;
  57114. var normal;
  57115. var rotated;
  57116. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57117. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57118. for (var i = 0; i < path.length; i++) {
  57119. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57120. circlePath = Array(); // current circle array
  57121. normal = normals[i]; // current normal
  57122. for (var t = 0; t < tessellation; t++) {
  57123. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57124. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57125. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57126. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57127. circlePath[t] = rotated;
  57128. }
  57129. circlePaths[index] = circlePath;
  57130. index++;
  57131. }
  57132. // cap
  57133. var capPath = function (nbPoints, pathIndex) {
  57134. var pointCap = Array();
  57135. for (var i = 0; i < nbPoints; i++) {
  57136. pointCap.push(path[pathIndex]);
  57137. }
  57138. return pointCap;
  57139. };
  57140. switch (cap) {
  57141. case BABYLON.Mesh.NO_CAP:
  57142. break;
  57143. case BABYLON.Mesh.CAP_START:
  57144. circlePaths[0] = capPath(tessellation, 0);
  57145. circlePaths[1] = circlePaths[2].slice(0);
  57146. break;
  57147. case BABYLON.Mesh.CAP_END:
  57148. circlePaths[index] = circlePaths[index - 1].slice(0);
  57149. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57150. break;
  57151. case BABYLON.Mesh.CAP_ALL:
  57152. circlePaths[0] = capPath(tessellation, 0);
  57153. circlePaths[1] = circlePaths[2].slice(0);
  57154. circlePaths[index] = circlePaths[index - 1].slice(0);
  57155. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57156. break;
  57157. default:
  57158. break;
  57159. }
  57160. return circlePaths;
  57161. };
  57162. var path3D;
  57163. var pathArray;
  57164. if (instance) {
  57165. var arc = options.arc || instance.arc;
  57166. path3D = (instance.path3D).update(path);
  57167. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57168. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57169. instance.path3D = path3D;
  57170. instance.pathArray = pathArray;
  57171. instance.arc = arc;
  57172. instance.radius = radius;
  57173. return instance;
  57174. }
  57175. // tube creation
  57176. path3D = new BABYLON.Path3D(path);
  57177. var newPathArray = new Array();
  57178. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57179. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57180. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57181. tube.pathArray = pathArray;
  57182. tube.path3D = path3D;
  57183. tube.tessellation = tessellation;
  57184. tube.cap = cap;
  57185. tube.arc = options.arc;
  57186. tube.radius = radius;
  57187. return tube;
  57188. };
  57189. /**
  57190. * Creates a polyhedron mesh.
  57191. *
  57192. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57193. * 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
  57194. * to choose the wanted type.
  57195. * The parameter `size` (positive float, default 1) sets the polygon size.
  57196. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57197. * 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`.
  57198. * 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
  57199. * 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)`).
  57200. * 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
  57201. * 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.
  57202. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57203. * 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).
  57204. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57205. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57206. */
  57207. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57208. var polyhedron = new BABYLON.Mesh(name, scene);
  57209. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57210. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57211. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57212. vertexData.applyToMesh(polyhedron, options.updatable);
  57213. return polyhedron;
  57214. };
  57215. /**
  57216. * Creates a decal mesh.
  57217. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57218. * 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.
  57219. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57220. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57221. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57222. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57223. */
  57224. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57225. var indices = sourceMesh.getIndices();
  57226. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57227. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57228. var position = options.position || BABYLON.Vector3.Zero();
  57229. var normal = options.normal || BABYLON.Vector3.Up();
  57230. var size = options.size || BABYLON.Vector3.One();
  57231. var angle = options.angle || 0;
  57232. // Getting correct rotation
  57233. if (!normal) {
  57234. var target = new BABYLON.Vector3(0, 0, 1);
  57235. var camera = sourceMesh.getScene().activeCamera;
  57236. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57237. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57238. }
  57239. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57240. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57241. var pitch = Math.atan2(normal.y, len);
  57242. // Matrix
  57243. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57244. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57245. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57246. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57247. var vertexData = new BABYLON.VertexData();
  57248. vertexData.indices = [];
  57249. vertexData.positions = [];
  57250. vertexData.normals = [];
  57251. vertexData.uvs = [];
  57252. var currentVertexDataIndex = 0;
  57253. var extractDecalVector3 = function (indexId) {
  57254. var result = new BABYLON.PositionNormalVertex();
  57255. if (!indices || !positions || !normals) {
  57256. return result;
  57257. }
  57258. var vertexId = indices[indexId];
  57259. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57260. // Send vector to decal local world
  57261. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57262. // Get normal
  57263. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57264. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57265. return result;
  57266. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57267. var clip = function (vertices, axis) {
  57268. if (vertices.length === 0) {
  57269. return vertices;
  57270. }
  57271. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57272. var clipVertices = function (v0, v1) {
  57273. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57274. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57275. };
  57276. var result = new Array();
  57277. for (var index = 0; index < vertices.length; index += 3) {
  57278. var v1Out;
  57279. var v2Out;
  57280. var v3Out;
  57281. var total = 0;
  57282. var nV1 = null;
  57283. var nV2 = null;
  57284. var nV3 = null;
  57285. var nV4 = null;
  57286. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57287. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57288. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57289. v1Out = d1 > 0;
  57290. v2Out = d2 > 0;
  57291. v3Out = d3 > 0;
  57292. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57293. switch (total) {
  57294. case 0:
  57295. result.push(vertices[index]);
  57296. result.push(vertices[index + 1]);
  57297. result.push(vertices[index + 2]);
  57298. break;
  57299. case 1:
  57300. if (v1Out) {
  57301. nV1 = vertices[index + 1];
  57302. nV2 = vertices[index + 2];
  57303. nV3 = clipVertices(vertices[index], nV1);
  57304. nV4 = clipVertices(vertices[index], nV2);
  57305. }
  57306. if (v2Out) {
  57307. nV1 = vertices[index];
  57308. nV2 = vertices[index + 2];
  57309. nV3 = clipVertices(vertices[index + 1], nV1);
  57310. nV4 = clipVertices(vertices[index + 1], nV2);
  57311. result.push(nV3);
  57312. result.push(nV2.clone());
  57313. result.push(nV1.clone());
  57314. result.push(nV2.clone());
  57315. result.push(nV3.clone());
  57316. result.push(nV4);
  57317. break;
  57318. }
  57319. if (v3Out) {
  57320. nV1 = vertices[index];
  57321. nV2 = vertices[index + 1];
  57322. nV3 = clipVertices(vertices[index + 2], nV1);
  57323. nV4 = clipVertices(vertices[index + 2], nV2);
  57324. }
  57325. if (nV1 && nV2 && nV3 && nV4) {
  57326. result.push(nV1.clone());
  57327. result.push(nV2.clone());
  57328. result.push(nV3);
  57329. result.push(nV4);
  57330. result.push(nV3.clone());
  57331. result.push(nV2.clone());
  57332. }
  57333. break;
  57334. case 2:
  57335. if (!v1Out) {
  57336. nV1 = vertices[index].clone();
  57337. nV2 = clipVertices(nV1, vertices[index + 1]);
  57338. nV3 = clipVertices(nV1, vertices[index + 2]);
  57339. result.push(nV1);
  57340. result.push(nV2);
  57341. result.push(nV3);
  57342. }
  57343. if (!v2Out) {
  57344. nV1 = vertices[index + 1].clone();
  57345. nV2 = clipVertices(nV1, vertices[index + 2]);
  57346. nV3 = clipVertices(nV1, vertices[index]);
  57347. result.push(nV1);
  57348. result.push(nV2);
  57349. result.push(nV3);
  57350. }
  57351. if (!v3Out) {
  57352. nV1 = vertices[index + 2].clone();
  57353. nV2 = clipVertices(nV1, vertices[index]);
  57354. nV3 = clipVertices(nV1, vertices[index + 1]);
  57355. result.push(nV1);
  57356. result.push(nV2);
  57357. result.push(nV3);
  57358. }
  57359. break;
  57360. case 3:
  57361. break;
  57362. }
  57363. }
  57364. return result;
  57365. };
  57366. for (var index = 0; index < indices.length; index += 3) {
  57367. var faceVertices = new Array();
  57368. faceVertices.push(extractDecalVector3(index));
  57369. faceVertices.push(extractDecalVector3(index + 1));
  57370. faceVertices.push(extractDecalVector3(index + 2));
  57371. // Clip
  57372. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57373. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57374. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57375. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57376. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57377. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57378. if (faceVertices.length === 0) {
  57379. continue;
  57380. }
  57381. // Add UVs and get back to world
  57382. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57383. var vertex = faceVertices[vIndex];
  57384. //TODO check for Int32Array | Uint32Array | Uint16Array
  57385. vertexData.indices.push(currentVertexDataIndex);
  57386. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57387. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57388. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57389. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57390. currentVertexDataIndex++;
  57391. }
  57392. }
  57393. // Return mesh
  57394. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57395. vertexData.applyToMesh(decal);
  57396. decal.position = position.clone();
  57397. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57398. return decal;
  57399. };
  57400. // Privates
  57401. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57402. // extrusion geometry
  57403. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57404. var tangents = path3D.getTangents();
  57405. var normals = path3D.getNormals();
  57406. var binormals = path3D.getBinormals();
  57407. var distances = path3D.getDistances();
  57408. var angle = 0;
  57409. var returnScale = function () { return scale !== null ? scale : 1; };
  57410. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57411. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57412. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57413. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57414. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57415. for (var i = 0; i < curve.length; i++) {
  57416. var shapePath = new Array();
  57417. var angleStep = rotate(i, distances[i]);
  57418. var scaleRatio = scl(i, distances[i]);
  57419. for (var p = 0; p < shape.length; p++) {
  57420. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57421. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57422. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57423. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57424. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57425. shapePath[p] = rotated;
  57426. }
  57427. shapePaths[index] = shapePath;
  57428. angle += angleStep;
  57429. index++;
  57430. }
  57431. // cap
  57432. var capPath = function (shapePath) {
  57433. var pointCap = Array();
  57434. var barycenter = BABYLON.Vector3.Zero();
  57435. var i;
  57436. for (i = 0; i < shapePath.length; i++) {
  57437. barycenter.addInPlace(shapePath[i]);
  57438. }
  57439. barycenter.scaleInPlace(1.0 / shapePath.length);
  57440. for (i = 0; i < shapePath.length; i++) {
  57441. pointCap.push(barycenter);
  57442. }
  57443. return pointCap;
  57444. };
  57445. switch (cap) {
  57446. case BABYLON.Mesh.NO_CAP:
  57447. break;
  57448. case BABYLON.Mesh.CAP_START:
  57449. shapePaths[0] = capPath(shapePaths[2]);
  57450. shapePaths[1] = shapePaths[2];
  57451. break;
  57452. case BABYLON.Mesh.CAP_END:
  57453. shapePaths[index] = shapePaths[index - 1];
  57454. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57455. break;
  57456. case BABYLON.Mesh.CAP_ALL:
  57457. shapePaths[0] = capPath(shapePaths[2]);
  57458. shapePaths[1] = shapePaths[2];
  57459. shapePaths[index] = shapePaths[index - 1];
  57460. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57461. break;
  57462. default:
  57463. break;
  57464. }
  57465. return shapePaths;
  57466. };
  57467. var path3D;
  57468. var pathArray;
  57469. if (instance) {
  57470. path3D = (instance.path3D).update(curve);
  57471. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57472. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57473. return instance;
  57474. }
  57475. // extruded shape creation
  57476. path3D = new BABYLON.Path3D(curve);
  57477. var newShapePaths = new Array();
  57478. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57479. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57480. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57481. extrudedGeneric.pathArray = pathArray;
  57482. extrudedGeneric.path3D = path3D;
  57483. extrudedGeneric.cap = cap;
  57484. return extrudedGeneric;
  57485. };
  57486. return MeshBuilder;
  57487. }());
  57488. BABYLON.MeshBuilder = MeshBuilder;
  57489. })(BABYLON || (BABYLON = {}));
  57490. //# sourceMappingURL=babylon.meshBuilder.js.map
  57491. "use strict";
  57492. var BABYLON;
  57493. (function (BABYLON) {
  57494. /**
  57495. * Draco compression (https://google.github.io/draco/)
  57496. */
  57497. var DracoCompression = /** @class */ (function () {
  57498. /**
  57499. * Constructor
  57500. * @param numWorkers The number of workers for async operations
  57501. */
  57502. function DracoCompression(numWorkers) {
  57503. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57504. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57505. if (!workerBlobUrl || !Worker) {
  57506. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57507. return;
  57508. }
  57509. var workers = new Array(numWorkers);
  57510. for (var i = 0; i < workers.length; i++) {
  57511. var worker = new Worker(workerBlobUrl);
  57512. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57513. workers[i] = worker;
  57514. }
  57515. this._workerPool = new BABYLON.WorkerPool(workers);
  57516. }
  57517. /**
  57518. * Stop all async operations and release resources.
  57519. */
  57520. DracoCompression.prototype.dispose = function () {
  57521. this._workerPool.dispose();
  57522. delete this._workerPool;
  57523. };
  57524. /**
  57525. * Decode Draco compressed mesh data to vertex data.
  57526. * @param data The array buffer view for the Draco compression data
  57527. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57528. * @returns A promise that resolves with the decoded vertex data
  57529. */
  57530. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57531. var _this = this;
  57532. return new Promise(function (resolve, reject) {
  57533. _this._workerPool.push(function (worker, onComplete) {
  57534. var vertexData = new BABYLON.VertexData();
  57535. var onError = function (error) {
  57536. worker.removeEventListener("error", onError);
  57537. worker.removeEventListener("message", onMessage);
  57538. reject(error);
  57539. onComplete();
  57540. };
  57541. var onMessage = function (message) {
  57542. if (message.data === "done") {
  57543. worker.removeEventListener("error", onError);
  57544. worker.removeEventListener("message", onMessage);
  57545. resolve(vertexData);
  57546. onComplete();
  57547. }
  57548. else if (message.data.id === "indices") {
  57549. vertexData.indices = message.data.value;
  57550. }
  57551. else {
  57552. vertexData.set(message.data.value, message.data.id);
  57553. }
  57554. };
  57555. worker.addEventListener("error", onError);
  57556. worker.addEventListener("message", onMessage);
  57557. var dataCopy = new Uint8Array(data.byteLength);
  57558. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57559. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57560. });
  57561. });
  57562. };
  57563. /**
  57564. * The worker function that gets converted to a blob url to pass into a worker.
  57565. */
  57566. DracoCompression._Worker = function () {
  57567. // self is actually a DedicatedWorkerGlobalScope
  57568. var _self = self;
  57569. var decodeMesh = function (data, attributes) {
  57570. var dracoModule = new DracoDecoderModule();
  57571. var buffer = new dracoModule.DecoderBuffer();
  57572. buffer.Init(data, data.byteLength);
  57573. var decoder = new dracoModule.Decoder();
  57574. var geometry;
  57575. var status;
  57576. try {
  57577. var type = decoder.GetEncodedGeometryType(buffer);
  57578. switch (type) {
  57579. case dracoModule.TRIANGULAR_MESH:
  57580. geometry = new dracoModule.Mesh();
  57581. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57582. break;
  57583. case dracoModule.POINT_CLOUD:
  57584. geometry = new dracoModule.PointCloud();
  57585. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57586. break;
  57587. default:
  57588. throw new Error("Invalid geometry type " + type);
  57589. }
  57590. if (!status.ok() || !geometry.ptr) {
  57591. throw new Error(status.error_msg());
  57592. }
  57593. var numPoints = geometry.num_points();
  57594. if (type === dracoModule.TRIANGULAR_MESH) {
  57595. var numFaces = geometry.num_faces();
  57596. var faceIndices = new dracoModule.DracoInt32Array();
  57597. try {
  57598. var indices = new Uint32Array(numFaces * 3);
  57599. for (var i = 0; i < numFaces; i++) {
  57600. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57601. var offset = i * 3;
  57602. indices[offset + 0] = faceIndices.GetValue(0);
  57603. indices[offset + 1] = faceIndices.GetValue(1);
  57604. indices[offset + 2] = faceIndices.GetValue(2);
  57605. }
  57606. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57607. }
  57608. finally {
  57609. dracoModule.destroy(faceIndices);
  57610. }
  57611. }
  57612. for (var kind in attributes) {
  57613. var uniqueId = attributes[kind];
  57614. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57615. var dracoData = new dracoModule.DracoFloat32Array();
  57616. try {
  57617. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57618. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57619. for (var i = 0; i < babylonData.length; i++) {
  57620. babylonData[i] = dracoData.GetValue(i);
  57621. }
  57622. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57623. }
  57624. finally {
  57625. dracoModule.destroy(dracoData);
  57626. }
  57627. }
  57628. }
  57629. finally {
  57630. if (geometry) {
  57631. dracoModule.destroy(geometry);
  57632. }
  57633. dracoModule.destroy(decoder);
  57634. dracoModule.destroy(buffer);
  57635. }
  57636. _self.postMessage("done");
  57637. };
  57638. _self.onmessage = function (event) {
  57639. switch (event.data.id) {
  57640. case "initDecoder": {
  57641. importScripts(event.data.url);
  57642. break;
  57643. }
  57644. case "decodeMesh": {
  57645. decodeMesh(event.data.data, event.data.attributes);
  57646. break;
  57647. }
  57648. }
  57649. };
  57650. };
  57651. DracoCompression._GetDefaultDecoderUrl = function () {
  57652. if (!BABYLON.Tools.IsWindowObjectExist) {
  57653. return null;
  57654. }
  57655. for (var i = 0; i < document.scripts.length; i++) {
  57656. if (document.scripts[i].type === "text/x-draco-decoder") {
  57657. return document.scripts[i].src;
  57658. }
  57659. }
  57660. return null;
  57661. };
  57662. /**
  57663. * Gets the url to the draco decoder if available.
  57664. */
  57665. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57666. return DracoCompression;
  57667. }());
  57668. BABYLON.DracoCompression = DracoCompression;
  57669. })(BABYLON || (BABYLON = {}));
  57670. //# sourceMappingURL=babylon.dracoCompression.js.map
  57671. "use strict";
  57672. var BABYLON;
  57673. (function (BABYLON) {
  57674. var AudioEngine = /** @class */ (function () {
  57675. function AudioEngine() {
  57676. this._audioContext = null;
  57677. this._audioContextInitialized = false;
  57678. this.canUseWebAudio = false;
  57679. this.WarnedWebAudioUnsupported = false;
  57680. this.unlocked = false;
  57681. this.isMP3supported = false;
  57682. this.isOGGsupported = false;
  57683. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57684. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57685. this.canUseWebAudio = true;
  57686. }
  57687. var audioElem = document.createElement('audio');
  57688. try {
  57689. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57690. this.isMP3supported = true;
  57691. }
  57692. }
  57693. catch (e) {
  57694. // protect error during capability check.
  57695. }
  57696. try {
  57697. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57698. this.isOGGsupported = true;
  57699. }
  57700. }
  57701. catch (e) {
  57702. // protect error during capability check.
  57703. }
  57704. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57705. this._unlockiOSaudio();
  57706. }
  57707. else {
  57708. this.unlocked = true;
  57709. }
  57710. }
  57711. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57712. get: function () {
  57713. if (!this._audioContextInitialized) {
  57714. this._initializeAudioContext();
  57715. }
  57716. return this._audioContext;
  57717. },
  57718. enumerable: true,
  57719. configurable: true
  57720. });
  57721. AudioEngine.prototype._unlockiOSaudio = function () {
  57722. var _this = this;
  57723. var unlockaudio = function () {
  57724. if (!_this.audioContext) {
  57725. return;
  57726. }
  57727. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57728. var source = _this.audioContext.createBufferSource();
  57729. source.buffer = buffer;
  57730. source.connect(_this.audioContext.destination);
  57731. source.start(0);
  57732. setTimeout(function () {
  57733. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57734. _this.unlocked = true;
  57735. window.removeEventListener('touchend', unlockaudio, false);
  57736. if (_this.onAudioUnlocked) {
  57737. _this.onAudioUnlocked();
  57738. }
  57739. }
  57740. }, 0);
  57741. };
  57742. window.addEventListener('touchend', unlockaudio, false);
  57743. };
  57744. AudioEngine.prototype._initializeAudioContext = function () {
  57745. try {
  57746. if (this.canUseWebAudio) {
  57747. this._audioContext = new AudioContext();
  57748. // create a global volume gain node
  57749. this.masterGain = this._audioContext.createGain();
  57750. this.masterGain.gain.value = 1;
  57751. this.masterGain.connect(this._audioContext.destination);
  57752. this._audioContextInitialized = true;
  57753. }
  57754. }
  57755. catch (e) {
  57756. this.canUseWebAudio = false;
  57757. BABYLON.Tools.Error("Web Audio: " + e.message);
  57758. }
  57759. };
  57760. AudioEngine.prototype.dispose = function () {
  57761. if (this.canUseWebAudio && this._audioContextInitialized) {
  57762. if (this._connectedAnalyser && this._audioContext) {
  57763. this._connectedAnalyser.stopDebugCanvas();
  57764. this._connectedAnalyser.dispose();
  57765. this.masterGain.disconnect();
  57766. this.masterGain.connect(this._audioContext.destination);
  57767. this._connectedAnalyser = null;
  57768. }
  57769. this.masterGain.gain.value = 1;
  57770. }
  57771. this.WarnedWebAudioUnsupported = false;
  57772. };
  57773. AudioEngine.prototype.getGlobalVolume = function () {
  57774. if (this.canUseWebAudio && this._audioContextInitialized) {
  57775. return this.masterGain.gain.value;
  57776. }
  57777. else {
  57778. return -1;
  57779. }
  57780. };
  57781. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57782. if (this.canUseWebAudio && this._audioContextInitialized) {
  57783. this.masterGain.gain.value = newVolume;
  57784. }
  57785. };
  57786. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57787. if (this._connectedAnalyser) {
  57788. this._connectedAnalyser.stopDebugCanvas();
  57789. }
  57790. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57791. this._connectedAnalyser = analyser;
  57792. this.masterGain.disconnect();
  57793. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57794. }
  57795. };
  57796. return AudioEngine;
  57797. }());
  57798. BABYLON.AudioEngine = AudioEngine;
  57799. })(BABYLON || (BABYLON = {}));
  57800. //# sourceMappingURL=babylon.audioEngine.js.map
  57801. "use strict";
  57802. var BABYLON;
  57803. (function (BABYLON) {
  57804. var Sound = /** @class */ (function () {
  57805. /**
  57806. * Create a sound and attach it to a scene
  57807. * @param name Name of your sound
  57808. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57809. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57810. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57811. */
  57812. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57813. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57814. var _this = this;
  57815. this.autoplay = false;
  57816. this.loop = false;
  57817. this.useCustomAttenuation = false;
  57818. this.spatialSound = false;
  57819. this.refDistance = 1;
  57820. this.rolloffFactor = 1;
  57821. this.maxDistance = 100;
  57822. this.distanceModel = "linear";
  57823. this._panningModel = "equalpower";
  57824. this._playbackRate = 1;
  57825. this._streaming = false;
  57826. this._startTime = 0;
  57827. this._startOffset = 0;
  57828. this._position = BABYLON.Vector3.Zero();
  57829. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57830. this._volume = 1;
  57831. this._isReadyToPlay = false;
  57832. this.isPlaying = false;
  57833. this.isPaused = false;
  57834. this._isDirectional = false;
  57835. // Used if you'd like to create a directional sound.
  57836. // If not set, the sound will be omnidirectional
  57837. this._coneInnerAngle = 360;
  57838. this._coneOuterAngle = 360;
  57839. this._coneOuterGain = 0;
  57840. this._isOutputConnected = false;
  57841. this._urlType = "Unknown";
  57842. this.name = name;
  57843. this._scene = scene;
  57844. this._readyToPlayCallback = readyToPlayCallback;
  57845. // Default custom attenuation function is a linear attenuation
  57846. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57847. if (currentDistance < maxDistance) {
  57848. return currentVolume * (1 - currentDistance / maxDistance);
  57849. }
  57850. else {
  57851. return 0;
  57852. }
  57853. };
  57854. if (options) {
  57855. this.autoplay = options.autoplay || false;
  57856. this.loop = options.loop || false;
  57857. // if volume === 0, we need another way to check this option
  57858. if (options.volume !== undefined) {
  57859. this._volume = options.volume;
  57860. }
  57861. this.spatialSound = options.spatialSound || false;
  57862. this.maxDistance = options.maxDistance || 100;
  57863. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57864. this.rolloffFactor = options.rolloffFactor || 1;
  57865. this.refDistance = options.refDistance || 1;
  57866. this.distanceModel = options.distanceModel || "linear";
  57867. this._playbackRate = options.playbackRate || 1;
  57868. this._streaming = options.streaming || false;
  57869. }
  57870. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57871. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57872. this._soundGain.gain.value = this._volume;
  57873. this._inputAudioNode = this._soundGain;
  57874. this._ouputAudioNode = this._soundGain;
  57875. if (this.spatialSound) {
  57876. this._createSpatialParameters();
  57877. }
  57878. this._scene.mainSoundTrack.AddSound(this);
  57879. var validParameter = true;
  57880. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57881. if (urlOrArrayBuffer) {
  57882. try {
  57883. if (typeof (urlOrArrayBuffer) === "string")
  57884. this._urlType = "String";
  57885. if (Array.isArray(urlOrArrayBuffer))
  57886. this._urlType = "Array";
  57887. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57888. this._urlType = "ArrayBuffer";
  57889. var urls = [];
  57890. var codecSupportedFound = false;
  57891. switch (this._urlType) {
  57892. case "ArrayBuffer":
  57893. if (urlOrArrayBuffer.byteLength > 0) {
  57894. codecSupportedFound = true;
  57895. this._soundLoaded(urlOrArrayBuffer);
  57896. }
  57897. break;
  57898. case "String":
  57899. urls.push(urlOrArrayBuffer);
  57900. case "Array":
  57901. if (urls.length === 0)
  57902. urls = urlOrArrayBuffer;
  57903. // If we found a supported format, we load it immediately and stop the loop
  57904. for (var i = 0; i < urls.length; i++) {
  57905. var url = urls[i];
  57906. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57907. codecSupportedFound = true;
  57908. }
  57909. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57910. codecSupportedFound = true;
  57911. }
  57912. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57913. codecSupportedFound = true;
  57914. }
  57915. if (url.indexOf("blob:") !== -1) {
  57916. codecSupportedFound = true;
  57917. }
  57918. if (codecSupportedFound) {
  57919. // Loading sound using XHR2
  57920. if (!this._streaming) {
  57921. this._scene._loadFile(url, function (data) {
  57922. _this._soundLoaded(data);
  57923. }, undefined, true, true, function (exception) {
  57924. if (exception) {
  57925. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  57926. }
  57927. BABYLON.Tools.Error("Sound creation aborted.");
  57928. _this._scene.mainSoundTrack.RemoveSound(_this);
  57929. });
  57930. }
  57931. else {
  57932. this._htmlAudioElement = new Audio(url);
  57933. this._htmlAudioElement.controls = false;
  57934. this._htmlAudioElement.loop = this.loop;
  57935. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57936. this._htmlAudioElement.preload = "auto";
  57937. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57938. _this._isReadyToPlay = true;
  57939. if (_this.autoplay) {
  57940. _this.play();
  57941. }
  57942. if (_this._readyToPlayCallback) {
  57943. _this._readyToPlayCallback();
  57944. }
  57945. });
  57946. document.body.appendChild(this._htmlAudioElement);
  57947. }
  57948. break;
  57949. }
  57950. }
  57951. break;
  57952. default:
  57953. validParameter = false;
  57954. break;
  57955. }
  57956. if (!validParameter) {
  57957. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57958. }
  57959. else {
  57960. if (!codecSupportedFound) {
  57961. this._isReadyToPlay = true;
  57962. // Simulating a ready to play event to avoid breaking code path
  57963. if (this._readyToPlayCallback) {
  57964. window.setTimeout(function () {
  57965. if (_this._readyToPlayCallback) {
  57966. _this._readyToPlayCallback();
  57967. }
  57968. }, 1000);
  57969. }
  57970. }
  57971. }
  57972. }
  57973. catch (ex) {
  57974. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  57975. this._scene.mainSoundTrack.RemoveSound(this);
  57976. }
  57977. }
  57978. }
  57979. else {
  57980. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57981. this._scene.mainSoundTrack.AddSound(this);
  57982. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57983. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57984. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57985. }
  57986. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57987. if (this._readyToPlayCallback) {
  57988. window.setTimeout(function () {
  57989. if (_this._readyToPlayCallback) {
  57990. _this._readyToPlayCallback();
  57991. }
  57992. }, 1000);
  57993. }
  57994. }
  57995. }
  57996. Sound.prototype.dispose = function () {
  57997. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57998. if (this.isPlaying) {
  57999. this.stop();
  58000. }
  58001. this._isReadyToPlay = false;
  58002. if (this.soundTrackId === -1) {
  58003. this._scene.mainSoundTrack.RemoveSound(this);
  58004. }
  58005. else {
  58006. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58007. }
  58008. if (this._soundGain) {
  58009. this._soundGain.disconnect();
  58010. this._soundGain = null;
  58011. }
  58012. if (this._soundPanner) {
  58013. this._soundPanner.disconnect();
  58014. this._soundPanner = null;
  58015. }
  58016. if (this._soundSource) {
  58017. this._soundSource.disconnect();
  58018. this._soundSource = null;
  58019. }
  58020. this._audioBuffer = null;
  58021. if (this._htmlAudioElement) {
  58022. this._htmlAudioElement.pause();
  58023. this._htmlAudioElement.src = "";
  58024. document.body.removeChild(this._htmlAudioElement);
  58025. }
  58026. if (this._connectedMesh && this._registerFunc) {
  58027. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58028. this._connectedMesh = null;
  58029. }
  58030. }
  58031. };
  58032. Sound.prototype.isReady = function () {
  58033. return this._isReadyToPlay;
  58034. };
  58035. Sound.prototype._soundLoaded = function (audioData) {
  58036. var _this = this;
  58037. if (!BABYLON.Engine.audioEngine.audioContext) {
  58038. return;
  58039. }
  58040. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58041. _this._audioBuffer = buffer;
  58042. _this._isReadyToPlay = true;
  58043. if (_this.autoplay) {
  58044. _this.play();
  58045. }
  58046. if (_this._readyToPlayCallback) {
  58047. _this._readyToPlayCallback();
  58048. }
  58049. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58050. };
  58051. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58052. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58053. this._audioBuffer = audioBuffer;
  58054. this._isReadyToPlay = true;
  58055. }
  58056. };
  58057. Sound.prototype.updateOptions = function (options) {
  58058. if (options) {
  58059. this.loop = options.loop || this.loop;
  58060. this.maxDistance = options.maxDistance || this.maxDistance;
  58061. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58062. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58063. this.refDistance = options.refDistance || this.refDistance;
  58064. this.distanceModel = options.distanceModel || this.distanceModel;
  58065. this._playbackRate = options.playbackRate || this._playbackRate;
  58066. this._updateSpatialParameters();
  58067. if (this.isPlaying) {
  58068. if (this._streaming) {
  58069. this._htmlAudioElement.playbackRate = this._playbackRate;
  58070. }
  58071. else {
  58072. if (this._soundSource) {
  58073. this._soundSource.playbackRate.value = this._playbackRate;
  58074. }
  58075. }
  58076. }
  58077. }
  58078. };
  58079. Sound.prototype._createSpatialParameters = function () {
  58080. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58081. if (this._scene.headphone) {
  58082. this._panningModel = "HRTF";
  58083. }
  58084. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58085. this._updateSpatialParameters();
  58086. this._soundPanner.connect(this._ouputAudioNode);
  58087. this._inputAudioNode = this._soundPanner;
  58088. }
  58089. };
  58090. Sound.prototype._updateSpatialParameters = function () {
  58091. if (this.spatialSound && this._soundPanner) {
  58092. if (this.useCustomAttenuation) {
  58093. // Tricks to disable in a way embedded Web Audio attenuation
  58094. this._soundPanner.distanceModel = "linear";
  58095. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58096. this._soundPanner.refDistance = 1;
  58097. this._soundPanner.rolloffFactor = 1;
  58098. this._soundPanner.panningModel = this._panningModel;
  58099. }
  58100. else {
  58101. this._soundPanner.distanceModel = this.distanceModel;
  58102. this._soundPanner.maxDistance = this.maxDistance;
  58103. this._soundPanner.refDistance = this.refDistance;
  58104. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58105. this._soundPanner.panningModel = this._panningModel;
  58106. }
  58107. }
  58108. };
  58109. Sound.prototype.switchPanningModelToHRTF = function () {
  58110. this._panningModel = "HRTF";
  58111. this._switchPanningModel();
  58112. };
  58113. Sound.prototype.switchPanningModelToEqualPower = function () {
  58114. this._panningModel = "equalpower";
  58115. this._switchPanningModel();
  58116. };
  58117. Sound.prototype._switchPanningModel = function () {
  58118. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58119. this._soundPanner.panningModel = this._panningModel;
  58120. }
  58121. };
  58122. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58123. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58124. if (this._isOutputConnected) {
  58125. this._ouputAudioNode.disconnect();
  58126. }
  58127. this._ouputAudioNode.connect(soundTrackAudioNode);
  58128. this._isOutputConnected = true;
  58129. }
  58130. };
  58131. /**
  58132. * Transform this sound into a directional source
  58133. * @param coneInnerAngle Size of the inner cone in degree
  58134. * @param coneOuterAngle Size of the outer cone in degree
  58135. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58136. */
  58137. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58138. if (coneOuterAngle < coneInnerAngle) {
  58139. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58140. return;
  58141. }
  58142. this._coneInnerAngle = coneInnerAngle;
  58143. this._coneOuterAngle = coneOuterAngle;
  58144. this._coneOuterGain = coneOuterGain;
  58145. this._isDirectional = true;
  58146. if (this.isPlaying && this.loop) {
  58147. this.stop();
  58148. this.play();
  58149. }
  58150. };
  58151. Sound.prototype.setPosition = function (newPosition) {
  58152. this._position = newPosition;
  58153. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58154. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58155. }
  58156. };
  58157. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58158. this._localDirection = newLocalDirection;
  58159. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58160. this._updateDirection();
  58161. }
  58162. };
  58163. Sound.prototype._updateDirection = function () {
  58164. if (!this._connectedMesh || !this._soundPanner) {
  58165. return;
  58166. }
  58167. var mat = this._connectedMesh.getWorldMatrix();
  58168. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58169. direction.normalize();
  58170. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58171. };
  58172. Sound.prototype.updateDistanceFromListener = function () {
  58173. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58174. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58175. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58176. }
  58177. };
  58178. Sound.prototype.setAttenuationFunction = function (callback) {
  58179. this._customAttenuationFunction = callback;
  58180. };
  58181. /**
  58182. * Play the sound
  58183. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58184. * @param offset (optional) Start the sound setting it at a specific time
  58185. */
  58186. Sound.prototype.play = function (time, offset) {
  58187. var _this = this;
  58188. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58189. try {
  58190. if (this._startOffset < 0) {
  58191. time = -this._startOffset;
  58192. this._startOffset = 0;
  58193. }
  58194. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58195. if (!this._soundSource || !this._streamingSource) {
  58196. if (this.spatialSound && this._soundPanner) {
  58197. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58198. if (this._isDirectional) {
  58199. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58200. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58201. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58202. if (this._connectedMesh) {
  58203. this._updateDirection();
  58204. }
  58205. else {
  58206. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58207. }
  58208. }
  58209. }
  58210. }
  58211. if (this._streaming) {
  58212. if (!this._streamingSource) {
  58213. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58214. this._htmlAudioElement.onended = function () { _this._onended(); };
  58215. this._htmlAudioElement.playbackRate = this._playbackRate;
  58216. }
  58217. this._streamingSource.disconnect();
  58218. this._streamingSource.connect(this._inputAudioNode);
  58219. this._htmlAudioElement.play();
  58220. }
  58221. else {
  58222. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58223. this._soundSource.buffer = this._audioBuffer;
  58224. this._soundSource.connect(this._inputAudioNode);
  58225. this._soundSource.loop = this.loop;
  58226. this._soundSource.playbackRate.value = this._playbackRate;
  58227. this._soundSource.onended = function () { _this._onended(); };
  58228. if (this._soundSource.buffer) {
  58229. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58230. }
  58231. }
  58232. this._startTime = startTime;
  58233. this.isPlaying = true;
  58234. this.isPaused = false;
  58235. }
  58236. catch (ex) {
  58237. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58238. }
  58239. }
  58240. };
  58241. Sound.prototype._onended = function () {
  58242. this.isPlaying = false;
  58243. if (this.onended) {
  58244. this.onended();
  58245. }
  58246. };
  58247. /**
  58248. * Stop the sound
  58249. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58250. */
  58251. Sound.prototype.stop = function (time) {
  58252. if (this.isPlaying) {
  58253. if (this._streaming) {
  58254. this._htmlAudioElement.pause();
  58255. // Test needed for Firefox or it will generate an Invalid State Error
  58256. if (this._htmlAudioElement.currentTime > 0) {
  58257. this._htmlAudioElement.currentTime = 0;
  58258. }
  58259. }
  58260. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58261. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58262. this._soundSource.stop(stopTime);
  58263. this._soundSource.onended = function () { };
  58264. if (!this.isPaused) {
  58265. this._startOffset = 0;
  58266. }
  58267. }
  58268. this.isPlaying = false;
  58269. }
  58270. };
  58271. Sound.prototype.pause = function () {
  58272. if (this.isPlaying) {
  58273. this.isPaused = true;
  58274. if (this._streaming) {
  58275. this._htmlAudioElement.pause();
  58276. }
  58277. else if (BABYLON.Engine.audioEngine.audioContext) {
  58278. this.stop(0);
  58279. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58280. }
  58281. }
  58282. };
  58283. Sound.prototype.setVolume = function (newVolume, time) {
  58284. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58285. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58286. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58287. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58288. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58289. }
  58290. else {
  58291. this._soundGain.gain.value = newVolume;
  58292. }
  58293. }
  58294. this._volume = newVolume;
  58295. };
  58296. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58297. this._playbackRate = newPlaybackRate;
  58298. if (this.isPlaying) {
  58299. if (this._streaming) {
  58300. this._htmlAudioElement.playbackRate = this._playbackRate;
  58301. }
  58302. else if (this._soundSource) {
  58303. this._soundSource.playbackRate.value = this._playbackRate;
  58304. }
  58305. }
  58306. };
  58307. Sound.prototype.getVolume = function () {
  58308. return this._volume;
  58309. };
  58310. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58311. var _this = this;
  58312. if (this._connectedMesh && this._registerFunc) {
  58313. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58314. this._registerFunc = null;
  58315. }
  58316. this._connectedMesh = meshToConnectTo;
  58317. if (!this.spatialSound) {
  58318. this.spatialSound = true;
  58319. this._createSpatialParameters();
  58320. if (this.isPlaying && this.loop) {
  58321. this.stop();
  58322. this.play();
  58323. }
  58324. }
  58325. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58326. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58327. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58328. };
  58329. Sound.prototype.detachFromMesh = function () {
  58330. if (this._connectedMesh && this._registerFunc) {
  58331. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58332. this._registerFunc = null;
  58333. this._connectedMesh = null;
  58334. }
  58335. };
  58336. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58337. if (!node.getBoundingInfo) {
  58338. return;
  58339. }
  58340. var mesh = node;
  58341. var boundingInfo = mesh.getBoundingInfo();
  58342. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58343. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58344. this._updateDirection();
  58345. }
  58346. };
  58347. Sound.prototype.clone = function () {
  58348. var _this = this;
  58349. if (!this._streaming) {
  58350. var setBufferAndRun = function () {
  58351. if (_this._isReadyToPlay) {
  58352. clonedSound._audioBuffer = _this.getAudioBuffer();
  58353. clonedSound._isReadyToPlay = true;
  58354. if (clonedSound.autoplay) {
  58355. clonedSound.play();
  58356. }
  58357. }
  58358. else {
  58359. window.setTimeout(setBufferAndRun, 300);
  58360. }
  58361. };
  58362. var currentOptions = {
  58363. autoplay: this.autoplay, loop: this.loop,
  58364. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58365. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58366. refDistance: this.refDistance, distanceModel: this.distanceModel
  58367. };
  58368. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58369. if (this.useCustomAttenuation) {
  58370. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58371. }
  58372. clonedSound.setPosition(this._position);
  58373. clonedSound.setPlaybackRate(this._playbackRate);
  58374. setBufferAndRun();
  58375. return clonedSound;
  58376. }
  58377. else {
  58378. return null;
  58379. }
  58380. };
  58381. Sound.prototype.getAudioBuffer = function () {
  58382. return this._audioBuffer;
  58383. };
  58384. Sound.prototype.serialize = function () {
  58385. var serializationObject = {
  58386. name: this.name,
  58387. url: this.name,
  58388. autoplay: this.autoplay,
  58389. loop: this.loop,
  58390. volume: this._volume,
  58391. spatialSound: this.spatialSound,
  58392. maxDistance: this.maxDistance,
  58393. rolloffFactor: this.rolloffFactor,
  58394. refDistance: this.refDistance,
  58395. distanceModel: this.distanceModel,
  58396. playbackRate: this._playbackRate,
  58397. panningModel: this._panningModel,
  58398. soundTrackId: this.soundTrackId
  58399. };
  58400. if (this.spatialSound) {
  58401. if (this._connectedMesh)
  58402. serializationObject.connectedMeshId = this._connectedMesh.id;
  58403. serializationObject.position = this._position.asArray();
  58404. serializationObject.refDistance = this.refDistance;
  58405. serializationObject.distanceModel = this.distanceModel;
  58406. serializationObject.isDirectional = this._isDirectional;
  58407. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58408. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58409. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58410. serializationObject.coneOuterGain = this._coneOuterGain;
  58411. }
  58412. return serializationObject;
  58413. };
  58414. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58415. var soundName = parsedSound.name;
  58416. var soundUrl;
  58417. if (parsedSound.url) {
  58418. soundUrl = rootUrl + parsedSound.url;
  58419. }
  58420. else {
  58421. soundUrl = rootUrl + soundName;
  58422. }
  58423. var options = {
  58424. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58425. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58426. rolloffFactor: parsedSound.rolloffFactor,
  58427. refDistance: parsedSound.refDistance,
  58428. distanceModel: parsedSound.distanceModel,
  58429. playbackRate: parsedSound.playbackRate
  58430. };
  58431. var newSound;
  58432. if (!sourceSound) {
  58433. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58434. scene._addPendingData(newSound);
  58435. }
  58436. else {
  58437. var setBufferAndRun = function () {
  58438. if (sourceSound._isReadyToPlay) {
  58439. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58440. newSound._isReadyToPlay = true;
  58441. if (newSound.autoplay) {
  58442. newSound.play();
  58443. }
  58444. }
  58445. else {
  58446. window.setTimeout(setBufferAndRun, 300);
  58447. }
  58448. };
  58449. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58450. setBufferAndRun();
  58451. }
  58452. if (parsedSound.position) {
  58453. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58454. newSound.setPosition(soundPosition);
  58455. }
  58456. if (parsedSound.isDirectional) {
  58457. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58458. if (parsedSound.localDirectionToMesh) {
  58459. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58460. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58461. }
  58462. }
  58463. if (parsedSound.connectedMeshId) {
  58464. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58465. if (connectedMesh) {
  58466. newSound.attachToMesh(connectedMesh);
  58467. }
  58468. }
  58469. return newSound;
  58470. };
  58471. return Sound;
  58472. }());
  58473. BABYLON.Sound = Sound;
  58474. })(BABYLON || (BABYLON = {}));
  58475. //# sourceMappingURL=babylon.sound.js.map
  58476. "use strict";
  58477. var BABYLON;
  58478. (function (BABYLON) {
  58479. var SoundTrack = /** @class */ (function () {
  58480. function SoundTrack(scene, options) {
  58481. this.id = -1;
  58482. this._isMainTrack = false;
  58483. this._isInitialized = false;
  58484. this._scene = scene;
  58485. this.soundCollection = new Array();
  58486. this._options = options;
  58487. if (!this._isMainTrack) {
  58488. this._scene.soundTracks.push(this);
  58489. this.id = this._scene.soundTracks.length - 1;
  58490. }
  58491. }
  58492. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58493. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58494. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58495. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58496. if (this._options) {
  58497. if (this._options.volume) {
  58498. this._outputAudioNode.gain.value = this._options.volume;
  58499. }
  58500. if (this._options.mainTrack) {
  58501. this._isMainTrack = this._options.mainTrack;
  58502. }
  58503. }
  58504. this._isInitialized = true;
  58505. }
  58506. };
  58507. SoundTrack.prototype.dispose = function () {
  58508. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58509. if (this._connectedAnalyser) {
  58510. this._connectedAnalyser.stopDebugCanvas();
  58511. }
  58512. while (this.soundCollection.length) {
  58513. this.soundCollection[0].dispose();
  58514. }
  58515. if (this._outputAudioNode) {
  58516. this._outputAudioNode.disconnect();
  58517. }
  58518. this._outputAudioNode = null;
  58519. }
  58520. };
  58521. SoundTrack.prototype.AddSound = function (sound) {
  58522. if (!this._isInitialized) {
  58523. this._initializeSoundTrackAudioGraph();
  58524. }
  58525. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58526. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58527. }
  58528. if (sound.soundTrackId) {
  58529. if (sound.soundTrackId === -1) {
  58530. this._scene.mainSoundTrack.RemoveSound(sound);
  58531. }
  58532. else {
  58533. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58534. }
  58535. }
  58536. this.soundCollection.push(sound);
  58537. sound.soundTrackId = this.id;
  58538. };
  58539. SoundTrack.prototype.RemoveSound = function (sound) {
  58540. var index = this.soundCollection.indexOf(sound);
  58541. if (index !== -1) {
  58542. this.soundCollection.splice(index, 1);
  58543. }
  58544. };
  58545. SoundTrack.prototype.setVolume = function (newVolume) {
  58546. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58547. this._outputAudioNode.gain.value = newVolume;
  58548. }
  58549. };
  58550. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58551. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58552. for (var i = 0; i < this.soundCollection.length; i++) {
  58553. this.soundCollection[i].switchPanningModelToHRTF();
  58554. }
  58555. }
  58556. };
  58557. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58558. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58559. for (var i = 0; i < this.soundCollection.length; i++) {
  58560. this.soundCollection[i].switchPanningModelToEqualPower();
  58561. }
  58562. }
  58563. };
  58564. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58565. if (this._connectedAnalyser) {
  58566. this._connectedAnalyser.stopDebugCanvas();
  58567. }
  58568. this._connectedAnalyser = analyser;
  58569. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58570. this._outputAudioNode.disconnect();
  58571. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58572. }
  58573. };
  58574. return SoundTrack;
  58575. }());
  58576. BABYLON.SoundTrack = SoundTrack;
  58577. })(BABYLON || (BABYLON = {}));
  58578. //# sourceMappingURL=babylon.soundtrack.js.map
  58579. "use strict";
  58580. var BABYLON;
  58581. (function (BABYLON) {
  58582. var Analyser = /** @class */ (function () {
  58583. function Analyser(scene) {
  58584. this.SMOOTHING = 0.75;
  58585. this.FFT_SIZE = 512;
  58586. this.BARGRAPHAMPLITUDE = 256;
  58587. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58588. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58589. this._scene = scene;
  58590. this._audioEngine = BABYLON.Engine.audioEngine;
  58591. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58592. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58593. this._webAudioAnalyser.minDecibels = -140;
  58594. this._webAudioAnalyser.maxDecibels = 0;
  58595. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58596. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58597. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58598. }
  58599. }
  58600. Analyser.prototype.getFrequencyBinCount = function () {
  58601. if (this._audioEngine.canUseWebAudio) {
  58602. return this._webAudioAnalyser.frequencyBinCount;
  58603. }
  58604. else {
  58605. return 0;
  58606. }
  58607. };
  58608. Analyser.prototype.getByteFrequencyData = function () {
  58609. if (this._audioEngine.canUseWebAudio) {
  58610. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58611. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58612. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58613. }
  58614. return this._byteFreqs;
  58615. };
  58616. Analyser.prototype.getByteTimeDomainData = function () {
  58617. if (this._audioEngine.canUseWebAudio) {
  58618. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58619. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58620. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58621. }
  58622. return this._byteTime;
  58623. };
  58624. Analyser.prototype.getFloatFrequencyData = function () {
  58625. if (this._audioEngine.canUseWebAudio) {
  58626. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58627. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58628. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58629. }
  58630. return this._floatFreqs;
  58631. };
  58632. Analyser.prototype.drawDebugCanvas = function () {
  58633. var _this = this;
  58634. if (this._audioEngine.canUseWebAudio) {
  58635. if (!this._debugCanvas) {
  58636. this._debugCanvas = document.createElement("canvas");
  58637. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58638. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58639. this._debugCanvas.style.position = "absolute";
  58640. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58641. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58642. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58643. document.body.appendChild(this._debugCanvas);
  58644. this._registerFunc = function () {
  58645. _this.drawDebugCanvas();
  58646. };
  58647. this._scene.registerBeforeRender(this._registerFunc);
  58648. }
  58649. if (this._registerFunc && this._debugCanvasContext) {
  58650. var workingArray = this.getByteFrequencyData();
  58651. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58652. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58653. // Draw the frequency domain chart.
  58654. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58655. var value = workingArray[i];
  58656. var percent = value / this.BARGRAPHAMPLITUDE;
  58657. var height = this.DEBUGCANVASSIZE.height * percent;
  58658. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58659. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58660. var hue = i / this.getFrequencyBinCount() * 360;
  58661. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58662. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58663. }
  58664. }
  58665. }
  58666. };
  58667. Analyser.prototype.stopDebugCanvas = function () {
  58668. if (this._debugCanvas) {
  58669. if (this._registerFunc) {
  58670. this._scene.unregisterBeforeRender(this._registerFunc);
  58671. this._registerFunc = null;
  58672. }
  58673. document.body.removeChild(this._debugCanvas);
  58674. this._debugCanvas = null;
  58675. this._debugCanvasContext = null;
  58676. }
  58677. };
  58678. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58679. if (this._audioEngine.canUseWebAudio) {
  58680. inputAudioNode.connect(this._webAudioAnalyser);
  58681. this._webAudioAnalyser.connect(outputAudioNode);
  58682. }
  58683. };
  58684. Analyser.prototype.dispose = function () {
  58685. if (this._audioEngine.canUseWebAudio) {
  58686. this._webAudioAnalyser.disconnect();
  58687. }
  58688. };
  58689. return Analyser;
  58690. }());
  58691. BABYLON.Analyser = Analyser;
  58692. })(BABYLON || (BABYLON = {}));
  58693. //# sourceMappingURL=babylon.analyser.js.map
  58694. "use strict";
  58695. var BABYLON;
  58696. (function (BABYLON) {
  58697. var CubeTexture = /** @class */ (function (_super) {
  58698. __extends(CubeTexture, _super);
  58699. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58700. if (extensions === void 0) { extensions = null; }
  58701. if (noMipmap === void 0) { noMipmap = false; }
  58702. if (files === void 0) { files = null; }
  58703. if (onLoad === void 0) { onLoad = null; }
  58704. if (onError === void 0) { onError = null; }
  58705. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58706. if (prefiltered === void 0) { prefiltered = false; }
  58707. if (forcedExtension === void 0) { forcedExtension = null; }
  58708. var _this = _super.call(this, scene) || this;
  58709. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58710. /**
  58711. * Gets or sets the center of the bounding box associated with the cube texture
  58712. * It must define where the camera used to render the texture was set
  58713. */
  58714. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58715. _this.name = rootUrl;
  58716. _this.url = rootUrl;
  58717. _this._noMipmap = noMipmap;
  58718. _this.hasAlpha = false;
  58719. _this._format = format;
  58720. _this._prefiltered = prefiltered;
  58721. _this.isCube = true;
  58722. _this._textureMatrix = BABYLON.Matrix.Identity();
  58723. if (prefiltered) {
  58724. _this.gammaSpace = false;
  58725. }
  58726. if (!rootUrl && !files) {
  58727. return _this;
  58728. }
  58729. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58730. var lastDot = rootUrl.lastIndexOf(".");
  58731. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58732. var isDDS = (extension === ".dds");
  58733. if (!files) {
  58734. if (!isDDS && !extensions) {
  58735. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58736. }
  58737. files = [];
  58738. if (extensions) {
  58739. for (var index = 0; index < extensions.length; index++) {
  58740. files.push(rootUrl + extensions[index]);
  58741. }
  58742. }
  58743. }
  58744. _this._files = files;
  58745. if (!_this._texture) {
  58746. if (!scene.useDelayedTextureLoading) {
  58747. if (prefiltered) {
  58748. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58749. }
  58750. else {
  58751. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58752. }
  58753. }
  58754. else {
  58755. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58756. }
  58757. }
  58758. else if (onLoad) {
  58759. if (_this._texture.isReady) {
  58760. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58761. }
  58762. else {
  58763. _this._texture.onLoadedObservable.add(onLoad);
  58764. }
  58765. }
  58766. return _this;
  58767. }
  58768. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58769. get: function () {
  58770. return this._boundingBoxSize;
  58771. },
  58772. /**
  58773. * Gets or sets the size of the bounding box associated with the cube texture
  58774. * When defined, the cubemap will switch to local mode
  58775. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58776. * @example https://www.babylonjs-playground.com/#RNASML
  58777. */
  58778. set: function (value) {
  58779. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58780. return;
  58781. }
  58782. this._boundingBoxSize = value;
  58783. var scene = this.getScene();
  58784. if (scene) {
  58785. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58786. }
  58787. },
  58788. enumerable: true,
  58789. configurable: true
  58790. });
  58791. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58792. var rootUrlKey = "";
  58793. files.forEach(function (url) { return rootUrlKey += url; });
  58794. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58795. };
  58796. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58797. if (forcedExtension === void 0) { forcedExtension = null; }
  58798. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58799. };
  58800. // Methods
  58801. CubeTexture.prototype.delayLoad = function () {
  58802. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58803. return;
  58804. }
  58805. var scene = this.getScene();
  58806. if (!scene) {
  58807. return;
  58808. }
  58809. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58810. this._texture = this._getFromCache(this.url, this._noMipmap);
  58811. if (!this._texture) {
  58812. if (this._prefiltered) {
  58813. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58814. }
  58815. else {
  58816. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58817. }
  58818. }
  58819. };
  58820. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58821. return this._textureMatrix;
  58822. };
  58823. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58824. this._textureMatrix = value;
  58825. };
  58826. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58827. var texture = BABYLON.SerializationHelper.Parse(function () {
  58828. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58829. }, parsedTexture, scene);
  58830. // Local Cubemaps
  58831. if (parsedTexture.boundingBoxPosition) {
  58832. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58833. }
  58834. if (parsedTexture.boundingBoxSize) {
  58835. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58836. }
  58837. // Animations
  58838. if (parsedTexture.animations) {
  58839. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58840. var parsedAnimation = parsedTexture.animations[animationIndex];
  58841. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58842. }
  58843. }
  58844. return texture;
  58845. };
  58846. CubeTexture.prototype.clone = function () {
  58847. var _this = this;
  58848. return BABYLON.SerializationHelper.Clone(function () {
  58849. var scene = _this.getScene();
  58850. if (!scene) {
  58851. return _this;
  58852. }
  58853. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58854. }, this);
  58855. };
  58856. return CubeTexture;
  58857. }(BABYLON.BaseTexture));
  58858. BABYLON.CubeTexture = CubeTexture;
  58859. })(BABYLON || (BABYLON = {}));
  58860. //# sourceMappingURL=babylon.cubeTexture.js.map
  58861. "use strict";
  58862. var BABYLON;
  58863. (function (BABYLON) {
  58864. var RenderTargetTexture = /** @class */ (function (_super) {
  58865. __extends(RenderTargetTexture, _super);
  58866. /**
  58867. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58868. * or used a shadow, depth texture...
  58869. * @param name The friendly name of the texture
  58870. * @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)
  58871. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58872. * @param generateMipMaps True if mip maps need to be generated after render.
  58873. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58874. * @param type The type of the buffer in the RTT (int, half float, float...)
  58875. * @param isCube True if a cube texture needs to be created
  58876. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58877. * @param generateDepthBuffer True to generate a depth buffer
  58878. * @param generateStencilBuffer True to generate a stencil buffer
  58879. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58880. */
  58881. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58882. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58883. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58884. if (isCube === void 0) { isCube = false; }
  58885. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58886. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58887. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58888. if (isMulti === void 0) { isMulti = false; }
  58889. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58890. _this.isCube = isCube;
  58891. /**
  58892. * Use this list to define the list of mesh you want to render.
  58893. */
  58894. _this.renderList = new Array();
  58895. _this.renderParticles = true;
  58896. _this.renderSprites = false;
  58897. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58898. _this.ignoreCameraViewport = false;
  58899. // Events
  58900. /**
  58901. * An event triggered when the texture is unbind.
  58902. * @type {BABYLON.Observable}
  58903. */
  58904. _this.onBeforeBindObservable = new BABYLON.Observable();
  58905. /**
  58906. * An event triggered when the texture is unbind.
  58907. * @type {BABYLON.Observable}
  58908. */
  58909. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58910. /**
  58911. * An event triggered before rendering the texture
  58912. * @type {BABYLON.Observable}
  58913. */
  58914. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58915. /**
  58916. * An event triggered after rendering the texture
  58917. * @type {BABYLON.Observable}
  58918. */
  58919. _this.onAfterRenderObservable = new BABYLON.Observable();
  58920. /**
  58921. * An event triggered after the texture clear
  58922. * @type {BABYLON.Observable}
  58923. */
  58924. _this.onClearObservable = new BABYLON.Observable();
  58925. _this._currentRefreshId = -1;
  58926. _this._refreshRate = 1;
  58927. _this._samples = 1;
  58928. /**
  58929. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58930. * It must define where the camera used to render the texture is set
  58931. */
  58932. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58933. scene = _this.getScene();
  58934. if (!scene) {
  58935. return _this;
  58936. }
  58937. _this._engine = scene.getEngine();
  58938. _this.name = name;
  58939. _this.isRenderTarget = true;
  58940. _this._initialSizeParameter = size;
  58941. _this._processSizeParameter(size);
  58942. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58943. });
  58944. _this._generateMipMaps = generateMipMaps ? true : false;
  58945. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58946. // Rendering groups
  58947. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58948. if (isMulti) {
  58949. return _this;
  58950. }
  58951. _this._renderTargetOptions = {
  58952. generateMipMaps: generateMipMaps,
  58953. type: type,
  58954. samplingMode: samplingMode,
  58955. generateDepthBuffer: generateDepthBuffer,
  58956. generateStencilBuffer: generateStencilBuffer
  58957. };
  58958. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58959. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58960. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58961. }
  58962. if (isCube) {
  58963. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58964. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58965. _this._textureMatrix = BABYLON.Matrix.Identity();
  58966. }
  58967. else {
  58968. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58969. }
  58970. return _this;
  58971. }
  58972. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58973. get: function () {
  58974. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58975. },
  58976. enumerable: true,
  58977. configurable: true
  58978. });
  58979. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58980. get: function () {
  58981. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58982. },
  58983. enumerable: true,
  58984. configurable: true
  58985. });
  58986. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58987. get: function () {
  58988. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58989. },
  58990. enumerable: true,
  58991. configurable: true
  58992. });
  58993. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58994. set: function (callback) {
  58995. if (this._onAfterUnbindObserver) {
  58996. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58997. }
  58998. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58999. },
  59000. enumerable: true,
  59001. configurable: true
  59002. });
  59003. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59004. set: function (callback) {
  59005. if (this._onBeforeRenderObserver) {
  59006. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59007. }
  59008. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59009. },
  59010. enumerable: true,
  59011. configurable: true
  59012. });
  59013. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59014. set: function (callback) {
  59015. if (this._onAfterRenderObserver) {
  59016. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59017. }
  59018. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59019. },
  59020. enumerable: true,
  59021. configurable: true
  59022. });
  59023. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59024. set: function (callback) {
  59025. if (this._onClearObserver) {
  59026. this.onClearObservable.remove(this._onClearObserver);
  59027. }
  59028. this._onClearObserver = this.onClearObservable.add(callback);
  59029. },
  59030. enumerable: true,
  59031. configurable: true
  59032. });
  59033. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59034. get: function () {
  59035. return this._renderTargetOptions;
  59036. },
  59037. enumerable: true,
  59038. configurable: true
  59039. });
  59040. RenderTargetTexture.prototype._onRatioRescale = function () {
  59041. if (this._sizeRatio) {
  59042. this.resize(this._initialSizeParameter);
  59043. }
  59044. };
  59045. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59046. get: function () {
  59047. return this._boundingBoxSize;
  59048. },
  59049. /**
  59050. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59051. * When defined, the cubemap will switch to local mode
  59052. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59053. * @example https://www.babylonjs-playground.com/#RNASML
  59054. */
  59055. set: function (value) {
  59056. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59057. return;
  59058. }
  59059. this._boundingBoxSize = value;
  59060. var scene = this.getScene();
  59061. if (scene) {
  59062. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59063. }
  59064. },
  59065. enumerable: true,
  59066. configurable: true
  59067. });
  59068. /**
  59069. * Creates a depth stencil texture.
  59070. * This is only available in WebGL 2 or with the depth texture extension available.
  59071. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59072. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59073. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59074. */
  59075. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59076. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59077. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59078. if (generateStencil === void 0) { generateStencil = false; }
  59079. if (!this.getScene()) {
  59080. return;
  59081. }
  59082. var engine = this.getScene().getEngine();
  59083. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59084. bilinearFiltering: bilinearFiltering,
  59085. comparisonFunction: comparisonFunction,
  59086. generateStencil: generateStencil,
  59087. isCube: this.isCube
  59088. });
  59089. engine.setFrameBufferDepthStencilTexture(this);
  59090. };
  59091. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59092. if (size.ratio) {
  59093. this._sizeRatio = size.ratio;
  59094. this._size = {
  59095. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59096. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59097. };
  59098. }
  59099. else {
  59100. this._size = size;
  59101. }
  59102. };
  59103. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59104. get: function () {
  59105. return this._samples;
  59106. },
  59107. set: function (value) {
  59108. if (this._samples === value) {
  59109. return;
  59110. }
  59111. var scene = this.getScene();
  59112. if (!scene) {
  59113. return;
  59114. }
  59115. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59116. },
  59117. enumerable: true,
  59118. configurable: true
  59119. });
  59120. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59121. this._currentRefreshId = -1;
  59122. };
  59123. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59124. get: function () {
  59125. return this._refreshRate;
  59126. },
  59127. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59128. set: function (value) {
  59129. this._refreshRate = value;
  59130. this.resetRefreshCounter();
  59131. },
  59132. enumerable: true,
  59133. configurable: true
  59134. });
  59135. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59136. if (!this._postProcessManager) {
  59137. var scene = this.getScene();
  59138. if (!scene) {
  59139. return;
  59140. }
  59141. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59142. this._postProcesses = new Array();
  59143. }
  59144. this._postProcesses.push(postProcess);
  59145. this._postProcesses[0].autoClear = false;
  59146. };
  59147. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59148. if (!this._postProcesses) {
  59149. return;
  59150. }
  59151. if (dispose) {
  59152. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59153. var postProcess = _a[_i];
  59154. postProcess.dispose();
  59155. }
  59156. }
  59157. this._postProcesses = [];
  59158. };
  59159. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59160. if (!this._postProcesses) {
  59161. return;
  59162. }
  59163. var index = this._postProcesses.indexOf(postProcess);
  59164. if (index === -1) {
  59165. return;
  59166. }
  59167. this._postProcesses.splice(index, 1);
  59168. if (this._postProcesses.length > 0) {
  59169. this._postProcesses[0].autoClear = false;
  59170. }
  59171. };
  59172. RenderTargetTexture.prototype._shouldRender = function () {
  59173. if (this._currentRefreshId === -1) {
  59174. this._currentRefreshId = 1;
  59175. return true;
  59176. }
  59177. if (this.refreshRate === this._currentRefreshId) {
  59178. this._currentRefreshId = 1;
  59179. return true;
  59180. }
  59181. this._currentRefreshId++;
  59182. return false;
  59183. };
  59184. RenderTargetTexture.prototype.getRenderSize = function () {
  59185. if (this._size.width) {
  59186. return this._size.width;
  59187. }
  59188. return this._size;
  59189. };
  59190. RenderTargetTexture.prototype.getRenderWidth = function () {
  59191. if (this._size.width) {
  59192. return this._size.width;
  59193. }
  59194. return this._size;
  59195. };
  59196. RenderTargetTexture.prototype.getRenderHeight = function () {
  59197. if (this._size.width) {
  59198. return this._size.height;
  59199. }
  59200. return this._size;
  59201. };
  59202. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59203. get: function () {
  59204. return true;
  59205. },
  59206. enumerable: true,
  59207. configurable: true
  59208. });
  59209. RenderTargetTexture.prototype.scale = function (ratio) {
  59210. var newSize = this.getRenderSize() * ratio;
  59211. this.resize(newSize);
  59212. };
  59213. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59214. if (this.isCube) {
  59215. return this._textureMatrix;
  59216. }
  59217. return _super.prototype.getReflectionTextureMatrix.call(this);
  59218. };
  59219. RenderTargetTexture.prototype.resize = function (size) {
  59220. this.releaseInternalTexture();
  59221. var scene = this.getScene();
  59222. if (!scene) {
  59223. return;
  59224. }
  59225. this._processSizeParameter(size);
  59226. if (this.isCube) {
  59227. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59228. }
  59229. else {
  59230. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59231. }
  59232. };
  59233. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59234. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59235. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59236. var scene = this.getScene();
  59237. if (!scene) {
  59238. return;
  59239. }
  59240. var engine = scene.getEngine();
  59241. if (this.useCameraPostProcesses !== undefined) {
  59242. useCameraPostProcess = this.useCameraPostProcesses;
  59243. }
  59244. if (this._waitingRenderList) {
  59245. this.renderList = [];
  59246. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59247. var id = this._waitingRenderList[index];
  59248. var mesh_1 = scene.getMeshByID(id);
  59249. if (mesh_1) {
  59250. this.renderList.push(mesh_1);
  59251. }
  59252. }
  59253. delete this._waitingRenderList;
  59254. }
  59255. // Is predicate defined?
  59256. if (this.renderListPredicate) {
  59257. if (this.renderList) {
  59258. this.renderList.splice(0); // Clear previous renderList
  59259. }
  59260. else {
  59261. this.renderList = [];
  59262. }
  59263. var scene = this.getScene();
  59264. if (!scene) {
  59265. return;
  59266. }
  59267. var sceneMeshes = scene.meshes;
  59268. for (var index = 0; index < sceneMeshes.length; index++) {
  59269. var mesh = sceneMeshes[index];
  59270. if (this.renderListPredicate(mesh)) {
  59271. this.renderList.push(mesh);
  59272. }
  59273. }
  59274. }
  59275. this.onBeforeBindObservable.notifyObservers(this);
  59276. // Set custom projection.
  59277. // Needs to be before binding to prevent changing the aspect ratio.
  59278. var camera;
  59279. if (this.activeCamera) {
  59280. camera = this.activeCamera;
  59281. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59282. if (this.activeCamera !== scene.activeCamera) {
  59283. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59284. }
  59285. }
  59286. else {
  59287. camera = scene.activeCamera;
  59288. if (camera) {
  59289. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59290. }
  59291. }
  59292. // Prepare renderingManager
  59293. this._renderingManager.reset();
  59294. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59295. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59296. var sceneRenderId = scene.getRenderId();
  59297. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59298. var mesh = currentRenderList[meshIndex];
  59299. if (mesh) {
  59300. if (!mesh.isReady(this.refreshRate === 0)) {
  59301. this.resetRefreshCounter();
  59302. continue;
  59303. }
  59304. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59305. var isMasked = void 0;
  59306. if (!this.renderList && camera) {
  59307. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59308. }
  59309. else {
  59310. isMasked = false;
  59311. }
  59312. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59313. mesh._activate(sceneRenderId);
  59314. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59315. var subMesh = mesh.subMeshes[subIndex];
  59316. scene._activeIndices.addCount(subMesh.indexCount, false);
  59317. this._renderingManager.dispatch(subMesh, mesh);
  59318. }
  59319. }
  59320. }
  59321. }
  59322. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59323. var particleSystem = scene.particleSystems[particleIndex];
  59324. var emitter = particleSystem.emitter;
  59325. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59326. continue;
  59327. }
  59328. if (currentRenderList.indexOf(emitter) >= 0) {
  59329. this._renderingManager.dispatchParticles(particleSystem);
  59330. }
  59331. }
  59332. if (this.isCube) {
  59333. for (var face = 0; face < 6; face++) {
  59334. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59335. scene.incrementRenderId();
  59336. scene.resetCachedMaterial();
  59337. }
  59338. }
  59339. else {
  59340. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59341. }
  59342. this.onAfterUnbindObservable.notifyObservers(this);
  59343. if (scene.activeCamera) {
  59344. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59345. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59346. }
  59347. engine.setViewport(scene.activeCamera.viewport);
  59348. }
  59349. scene.resetCachedMaterial();
  59350. };
  59351. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59352. var minimum = 128;
  59353. var x = renderDimension * scale;
  59354. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59355. // Ensure we don't exceed the render dimension (while staying POT)
  59356. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59357. };
  59358. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59359. var _this = this;
  59360. if (!this._texture) {
  59361. return;
  59362. }
  59363. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59364. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59365. });
  59366. };
  59367. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59368. var scene = this.getScene();
  59369. if (!scene) {
  59370. return;
  59371. }
  59372. var engine = scene.getEngine();
  59373. if (!this._texture) {
  59374. return;
  59375. }
  59376. // Bind
  59377. if (this._postProcessManager) {
  59378. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59379. }
  59380. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59381. if (this._texture) {
  59382. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59383. }
  59384. }
  59385. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59386. // Clear
  59387. if (this.onClearObservable.hasObservers()) {
  59388. this.onClearObservable.notifyObservers(engine);
  59389. }
  59390. else {
  59391. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59392. }
  59393. if (!this._doNotChangeAspectRatio) {
  59394. scene.updateTransformMatrix(true);
  59395. }
  59396. // Render
  59397. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59398. if (this._postProcessManager) {
  59399. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59400. }
  59401. else if (useCameraPostProcess) {
  59402. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59403. }
  59404. if (!this._doNotChangeAspectRatio) {
  59405. scene.updateTransformMatrix(true);
  59406. }
  59407. // Dump ?
  59408. if (dumpForDebug) {
  59409. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59410. }
  59411. // Unbind
  59412. if (!this.isCube || faceIndex === 5) {
  59413. if (this.isCube) {
  59414. if (faceIndex === 5) {
  59415. engine.generateMipMapsForCubemap(this._texture);
  59416. }
  59417. }
  59418. this.unbindFrameBuffer(engine, faceIndex);
  59419. }
  59420. else {
  59421. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59422. }
  59423. };
  59424. /**
  59425. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59426. * This allowed control for front to back rendering or reversly depending of the special needs.
  59427. *
  59428. * @param renderingGroupId The rendering group id corresponding to its index
  59429. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59430. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59431. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59432. */
  59433. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59434. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59435. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59436. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59437. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59438. };
  59439. /**
  59440. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59441. *
  59442. * @param renderingGroupId The rendering group id corresponding to its index
  59443. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59444. */
  59445. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59446. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59447. };
  59448. RenderTargetTexture.prototype.clone = function () {
  59449. var textureSize = this.getSize();
  59450. 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);
  59451. // Base texture
  59452. newTexture.hasAlpha = this.hasAlpha;
  59453. newTexture.level = this.level;
  59454. // RenderTarget Texture
  59455. newTexture.coordinatesMode = this.coordinatesMode;
  59456. if (this.renderList) {
  59457. newTexture.renderList = this.renderList.slice(0);
  59458. }
  59459. return newTexture;
  59460. };
  59461. RenderTargetTexture.prototype.serialize = function () {
  59462. if (!this.name) {
  59463. return null;
  59464. }
  59465. var serializationObject = _super.prototype.serialize.call(this);
  59466. serializationObject.renderTargetSize = this.getRenderSize();
  59467. serializationObject.renderList = [];
  59468. if (this.renderList) {
  59469. for (var index = 0; index < this.renderList.length; index++) {
  59470. serializationObject.renderList.push(this.renderList[index].id);
  59471. }
  59472. }
  59473. return serializationObject;
  59474. };
  59475. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59476. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59477. var objBuffer = this.getInternalTexture();
  59478. var scene = this.getScene();
  59479. if (objBuffer && scene) {
  59480. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59481. }
  59482. };
  59483. RenderTargetTexture.prototype.dispose = function () {
  59484. if (this._postProcessManager) {
  59485. this._postProcessManager.dispose();
  59486. this._postProcessManager = null;
  59487. }
  59488. this.clearPostProcesses(true);
  59489. if (this._resizeObserver) {
  59490. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59491. this._resizeObserver = null;
  59492. }
  59493. this.renderList = null;
  59494. // Remove from custom render targets
  59495. var scene = this.getScene();
  59496. if (!scene) {
  59497. return;
  59498. }
  59499. var index = scene.customRenderTargets.indexOf(this);
  59500. if (index >= 0) {
  59501. scene.customRenderTargets.splice(index, 1);
  59502. }
  59503. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59504. var camera = _a[_i];
  59505. index = camera.customRenderTargets.indexOf(this);
  59506. if (index >= 0) {
  59507. camera.customRenderTargets.splice(index, 1);
  59508. }
  59509. }
  59510. _super.prototype.dispose.call(this);
  59511. };
  59512. RenderTargetTexture.prototype._rebuild = function () {
  59513. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59514. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59515. }
  59516. if (this._postProcessManager) {
  59517. this._postProcessManager._rebuild();
  59518. }
  59519. };
  59520. /**
  59521. * Clear the info related to rendering groups preventing retention point in material dispose.
  59522. */
  59523. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59524. if (this._renderingManager) {
  59525. this._renderingManager.freeRenderingGroups();
  59526. }
  59527. };
  59528. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59529. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59530. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59531. return RenderTargetTexture;
  59532. }(BABYLON.Texture));
  59533. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59534. })(BABYLON || (BABYLON = {}));
  59535. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59536. "use strict";
  59537. var BABYLON;
  59538. (function (BABYLON) {
  59539. ;
  59540. var MultiRenderTarget = /** @class */ (function (_super) {
  59541. __extends(MultiRenderTarget, _super);
  59542. function MultiRenderTarget(name, size, count, scene, options) {
  59543. var _this = this;
  59544. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59545. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59546. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59547. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59548. _this._engine = scene.getEngine();
  59549. if (!_this.isSupported) {
  59550. _this.dispose();
  59551. return;
  59552. }
  59553. var types = [];
  59554. var samplingModes = [];
  59555. for (var i = 0; i < count; i++) {
  59556. if (options && options.types && options.types[i] !== undefined) {
  59557. types.push(options.types[i]);
  59558. }
  59559. else {
  59560. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59561. }
  59562. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59563. samplingModes.push(options.samplingModes[i]);
  59564. }
  59565. else {
  59566. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59567. }
  59568. }
  59569. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59570. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59571. _this._size = size;
  59572. _this._multiRenderTargetOptions = {
  59573. samplingModes: samplingModes,
  59574. generateMipMaps: generateMipMaps,
  59575. generateDepthBuffer: generateDepthBuffer,
  59576. generateStencilBuffer: generateStencilBuffer,
  59577. generateDepthTexture: generateDepthTexture,
  59578. types: types,
  59579. textureCount: count
  59580. };
  59581. _this._createInternalTextures();
  59582. _this._createTextures();
  59583. return _this;
  59584. }
  59585. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59586. get: function () {
  59587. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59588. },
  59589. enumerable: true,
  59590. configurable: true
  59591. });
  59592. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59593. get: function () {
  59594. return this._textures;
  59595. },
  59596. enumerable: true,
  59597. configurable: true
  59598. });
  59599. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59600. get: function () {
  59601. return this._textures[this._textures.length - 1];
  59602. },
  59603. enumerable: true,
  59604. configurable: true
  59605. });
  59606. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59607. set: function (wrap) {
  59608. if (this._textures) {
  59609. for (var i = 0; i < this._textures.length; i++) {
  59610. this._textures[i].wrapU = wrap;
  59611. }
  59612. }
  59613. },
  59614. enumerable: true,
  59615. configurable: true
  59616. });
  59617. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59618. set: function (wrap) {
  59619. if (this._textures) {
  59620. for (var i = 0; i < this._textures.length; i++) {
  59621. this._textures[i].wrapV = wrap;
  59622. }
  59623. }
  59624. },
  59625. enumerable: true,
  59626. configurable: true
  59627. });
  59628. MultiRenderTarget.prototype._rebuild = function () {
  59629. this.releaseInternalTextures();
  59630. this._createInternalTextures();
  59631. for (var i = 0; i < this._internalTextures.length; i++) {
  59632. var texture = this._textures[i];
  59633. texture._texture = this._internalTextures[i];
  59634. }
  59635. // Keeps references to frame buffer and stencil/depth buffer
  59636. this._texture = this._internalTextures[0];
  59637. };
  59638. MultiRenderTarget.prototype._createInternalTextures = function () {
  59639. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59640. };
  59641. MultiRenderTarget.prototype._createTextures = function () {
  59642. this._textures = [];
  59643. for (var i = 0; i < this._internalTextures.length; i++) {
  59644. var texture = new BABYLON.Texture(null, this.getScene());
  59645. texture._texture = this._internalTextures[i];
  59646. this._textures.push(texture);
  59647. }
  59648. // Keeps references to frame buffer and stencil/depth buffer
  59649. this._texture = this._internalTextures[0];
  59650. };
  59651. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59652. get: function () {
  59653. return this._samples;
  59654. },
  59655. set: function (value) {
  59656. if (this._samples === value) {
  59657. return;
  59658. }
  59659. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59660. },
  59661. enumerable: true,
  59662. configurable: true
  59663. });
  59664. MultiRenderTarget.prototype.resize = function (size) {
  59665. this.releaseInternalTextures();
  59666. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59667. this._createInternalTextures();
  59668. };
  59669. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59670. var _this = this;
  59671. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59672. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59673. });
  59674. };
  59675. MultiRenderTarget.prototype.dispose = function () {
  59676. this.releaseInternalTextures();
  59677. _super.prototype.dispose.call(this);
  59678. };
  59679. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59680. if (!this._internalTextures) {
  59681. return;
  59682. }
  59683. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59684. if (this._internalTextures[i] !== undefined) {
  59685. this._internalTextures[i].dispose();
  59686. this._internalTextures.splice(i, 1);
  59687. }
  59688. }
  59689. };
  59690. return MultiRenderTarget;
  59691. }(BABYLON.RenderTargetTexture));
  59692. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59693. })(BABYLON || (BABYLON = {}));
  59694. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59695. "use strict";
  59696. var BABYLON;
  59697. (function (BABYLON) {
  59698. var MirrorTexture = /** @class */ (function (_super) {
  59699. __extends(MirrorTexture, _super);
  59700. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59701. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59702. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59703. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59704. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59705. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59706. _this._transformMatrix = BABYLON.Matrix.Zero();
  59707. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59708. _this._adaptiveBlurKernel = 0;
  59709. _this._blurKernelX = 0;
  59710. _this._blurKernelY = 0;
  59711. _this._blurRatio = 1.0;
  59712. _this.ignoreCameraViewport = true;
  59713. _this.onBeforeRenderObservable.add(function () {
  59714. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59715. _this._savedViewMatrix = scene.getViewMatrix();
  59716. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59717. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59718. scene.clipPlane = _this.mirrorPlane;
  59719. scene.getEngine().cullBackFaces = false;
  59720. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59721. });
  59722. _this.onAfterRenderObservable.add(function () {
  59723. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59724. scene.getEngine().cullBackFaces = true;
  59725. scene._mirroredCameraPosition = null;
  59726. delete scene.clipPlane;
  59727. });
  59728. return _this;
  59729. }
  59730. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59731. get: function () {
  59732. return this._blurRatio;
  59733. },
  59734. set: function (value) {
  59735. if (this._blurRatio === value) {
  59736. return;
  59737. }
  59738. this._blurRatio = value;
  59739. this._preparePostProcesses();
  59740. },
  59741. enumerable: true,
  59742. configurable: true
  59743. });
  59744. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59745. set: function (value) {
  59746. this._adaptiveBlurKernel = value;
  59747. this._autoComputeBlurKernel();
  59748. },
  59749. enumerable: true,
  59750. configurable: true
  59751. });
  59752. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59753. set: function (value) {
  59754. this.blurKernelX = value;
  59755. this.blurKernelY = value;
  59756. },
  59757. enumerable: true,
  59758. configurable: true
  59759. });
  59760. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59761. get: function () {
  59762. return this._blurKernelX;
  59763. },
  59764. set: function (value) {
  59765. if (this._blurKernelX === value) {
  59766. return;
  59767. }
  59768. this._blurKernelX = value;
  59769. this._preparePostProcesses();
  59770. },
  59771. enumerable: true,
  59772. configurable: true
  59773. });
  59774. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59775. get: function () {
  59776. return this._blurKernelY;
  59777. },
  59778. set: function (value) {
  59779. if (this._blurKernelY === value) {
  59780. return;
  59781. }
  59782. this._blurKernelY = value;
  59783. this._preparePostProcesses();
  59784. },
  59785. enumerable: true,
  59786. configurable: true
  59787. });
  59788. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59789. var engine = this.getScene().getEngine();
  59790. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59791. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59792. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59793. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59794. };
  59795. MirrorTexture.prototype._onRatioRescale = function () {
  59796. if (this._sizeRatio) {
  59797. this.resize(this._initialSizeParameter);
  59798. if (!this._adaptiveBlurKernel) {
  59799. this._preparePostProcesses();
  59800. }
  59801. }
  59802. if (this._adaptiveBlurKernel) {
  59803. this._autoComputeBlurKernel();
  59804. }
  59805. };
  59806. MirrorTexture.prototype._preparePostProcesses = function () {
  59807. this.clearPostProcesses(true);
  59808. if (this._blurKernelX && this._blurKernelY) {
  59809. var engine = this.getScene().getEngine();
  59810. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59811. 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);
  59812. this._blurX.autoClear = false;
  59813. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59814. this._blurX.inputTexture = this._texture;
  59815. }
  59816. else {
  59817. this._blurX.alwaysForcePOT = true;
  59818. }
  59819. 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);
  59820. this._blurY.autoClear = false;
  59821. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59822. this.addPostProcess(this._blurX);
  59823. this.addPostProcess(this._blurY);
  59824. }
  59825. else {
  59826. if (this._blurY) {
  59827. this.removePostProcess(this._blurY);
  59828. this._blurY.dispose();
  59829. this._blurY = null;
  59830. }
  59831. if (this._blurX) {
  59832. this.removePostProcess(this._blurX);
  59833. this._blurX.dispose();
  59834. this._blurX = null;
  59835. }
  59836. }
  59837. };
  59838. MirrorTexture.prototype.clone = function () {
  59839. var scene = this.getScene();
  59840. if (!scene) {
  59841. return this;
  59842. }
  59843. var textureSize = this.getSize();
  59844. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59845. // Base texture
  59846. newTexture.hasAlpha = this.hasAlpha;
  59847. newTexture.level = this.level;
  59848. // Mirror Texture
  59849. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59850. if (this.renderList) {
  59851. newTexture.renderList = this.renderList.slice(0);
  59852. }
  59853. return newTexture;
  59854. };
  59855. MirrorTexture.prototype.serialize = function () {
  59856. if (!this.name) {
  59857. return null;
  59858. }
  59859. var serializationObject = _super.prototype.serialize.call(this);
  59860. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59861. return serializationObject;
  59862. };
  59863. return MirrorTexture;
  59864. }(BABYLON.RenderTargetTexture));
  59865. BABYLON.MirrorTexture = MirrorTexture;
  59866. })(BABYLON || (BABYLON = {}));
  59867. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59868. "use strict";
  59869. var BABYLON;
  59870. (function (BABYLON) {
  59871. /**
  59872. * Creates a refraction texture used by refraction channel of the standard material.
  59873. * @param name the texture name
  59874. * @param size size of the underlying texture
  59875. * @param scene root scene
  59876. */
  59877. var RefractionTexture = /** @class */ (function (_super) {
  59878. __extends(RefractionTexture, _super);
  59879. function RefractionTexture(name, size, scene, generateMipMaps) {
  59880. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59881. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59882. _this.depth = 2.0;
  59883. _this.onBeforeRenderObservable.add(function () {
  59884. scene.clipPlane = _this.refractionPlane;
  59885. });
  59886. _this.onAfterRenderObservable.add(function () {
  59887. delete scene.clipPlane;
  59888. });
  59889. return _this;
  59890. }
  59891. RefractionTexture.prototype.clone = function () {
  59892. var scene = this.getScene();
  59893. if (!scene) {
  59894. return this;
  59895. }
  59896. var textureSize = this.getSize();
  59897. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59898. // Base texture
  59899. newTexture.hasAlpha = this.hasAlpha;
  59900. newTexture.level = this.level;
  59901. // Refraction Texture
  59902. newTexture.refractionPlane = this.refractionPlane.clone();
  59903. if (this.renderList) {
  59904. newTexture.renderList = this.renderList.slice(0);
  59905. }
  59906. newTexture.depth = this.depth;
  59907. return newTexture;
  59908. };
  59909. RefractionTexture.prototype.serialize = function () {
  59910. if (!this.name) {
  59911. return null;
  59912. }
  59913. var serializationObject = _super.prototype.serialize.call(this);
  59914. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59915. serializationObject.depth = this.depth;
  59916. return serializationObject;
  59917. };
  59918. return RefractionTexture;
  59919. }(BABYLON.RenderTargetTexture));
  59920. BABYLON.RefractionTexture = RefractionTexture;
  59921. })(BABYLON || (BABYLON = {}));
  59922. //# sourceMappingURL=babylon.refractionTexture.js.map
  59923. "use strict";
  59924. var BABYLON;
  59925. (function (BABYLON) {
  59926. var DynamicTexture = /** @class */ (function (_super) {
  59927. __extends(DynamicTexture, _super);
  59928. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59929. if (scene === void 0) { scene = null; }
  59930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59931. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59932. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59933. _this.name = name;
  59934. _this._engine = _this.getScene().getEngine();
  59935. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59936. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59937. _this._generateMipMaps = generateMipMaps;
  59938. if (options.getContext) {
  59939. _this._canvas = options;
  59940. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59941. }
  59942. else {
  59943. _this._canvas = document.createElement("canvas");
  59944. if (options.width) {
  59945. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59946. }
  59947. else {
  59948. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59949. }
  59950. }
  59951. var textureSize = _this.getSize();
  59952. _this._canvas.width = textureSize.width;
  59953. _this._canvas.height = textureSize.height;
  59954. _this._context = _this._canvas.getContext("2d");
  59955. return _this;
  59956. }
  59957. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59958. get: function () {
  59959. return true;
  59960. },
  59961. enumerable: true,
  59962. configurable: true
  59963. });
  59964. DynamicTexture.prototype._recreate = function (textureSize) {
  59965. this._canvas.width = textureSize.width;
  59966. this._canvas.height = textureSize.height;
  59967. this.releaseInternalTexture();
  59968. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59969. };
  59970. DynamicTexture.prototype.scale = function (ratio) {
  59971. var textureSize = this.getSize();
  59972. textureSize.width *= ratio;
  59973. textureSize.height *= ratio;
  59974. this._recreate(textureSize);
  59975. };
  59976. DynamicTexture.prototype.scaleTo = function (width, height) {
  59977. var textureSize = this.getSize();
  59978. textureSize.width = width;
  59979. textureSize.height = height;
  59980. this._recreate(textureSize);
  59981. };
  59982. DynamicTexture.prototype.getContext = function () {
  59983. return this._context;
  59984. };
  59985. DynamicTexture.prototype.clear = function () {
  59986. var size = this.getSize();
  59987. this._context.fillRect(0, 0, size.width, size.height);
  59988. };
  59989. DynamicTexture.prototype.update = function (invertY) {
  59990. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59991. };
  59992. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59993. if (update === void 0) { update = true; }
  59994. var size = this.getSize();
  59995. if (clearColor) {
  59996. this._context.fillStyle = clearColor;
  59997. this._context.fillRect(0, 0, size.width, size.height);
  59998. }
  59999. this._context.font = font;
  60000. if (x === null || x === undefined) {
  60001. var textSize = this._context.measureText(text);
  60002. x = (size.width - textSize.width) / 2;
  60003. }
  60004. if (y === null || y === undefined) {
  60005. var fontSize = parseInt((font.replace(/\D/g, '')));
  60006. ;
  60007. y = (size.height / 2) + (fontSize / 3.65);
  60008. }
  60009. this._context.fillStyle = color;
  60010. this._context.fillText(text, x, y);
  60011. if (update) {
  60012. this.update(invertY);
  60013. }
  60014. };
  60015. DynamicTexture.prototype.clone = function () {
  60016. var scene = this.getScene();
  60017. if (!scene) {
  60018. return this;
  60019. }
  60020. var textureSize = this.getSize();
  60021. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  60022. // Base texture
  60023. newTexture.hasAlpha = this.hasAlpha;
  60024. newTexture.level = this.level;
  60025. // Dynamic Texture
  60026. newTexture.wrapU = this.wrapU;
  60027. newTexture.wrapV = this.wrapV;
  60028. return newTexture;
  60029. };
  60030. DynamicTexture.prototype._rebuild = function () {
  60031. this.update();
  60032. };
  60033. return DynamicTexture;
  60034. }(BABYLON.Texture));
  60035. BABYLON.DynamicTexture = DynamicTexture;
  60036. })(BABYLON || (BABYLON = {}));
  60037. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60038. "use strict";
  60039. var BABYLON;
  60040. (function (BABYLON) {
  60041. var VideoTexture = /** @class */ (function (_super) {
  60042. __extends(VideoTexture, _super);
  60043. /**
  60044. * Creates a video texture.
  60045. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60046. * @param {string | null} name optional name, will detect from video source, if not defined
  60047. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60048. * @param {BABYLON.Scene} scene is obviously the current scene.
  60049. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60050. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60051. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60052. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60053. */
  60054. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60055. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60056. if (invertY === void 0) { invertY = false; }
  60057. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60058. if (settings === void 0) { settings = {
  60059. autoPlay: true,
  60060. loop: true,
  60061. autoUpdateTexture: true,
  60062. }; }
  60063. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60064. _this._createInternalTexture = function () {
  60065. if (_this._texture != null) {
  60066. return;
  60067. }
  60068. if (!_this._engine.needPOTTextures ||
  60069. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60070. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60071. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60072. }
  60073. else {
  60074. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60075. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60076. _this._generateMipMaps = false;
  60077. }
  60078. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60079. _this._texture.isReady = true;
  60080. _this._updateInternalTexture();
  60081. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60082. _this.onLoadObservable.notifyObservers(_this);
  60083. }
  60084. };
  60085. _this.reset = function () {
  60086. if (_this._texture == null) {
  60087. return;
  60088. }
  60089. _this._texture.dispose();
  60090. _this._texture = null;
  60091. };
  60092. _this._updateInternalTexture = function (e) {
  60093. if (_this._texture == null || !_this._texture.isReady) {
  60094. return;
  60095. }
  60096. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60097. return;
  60098. }
  60099. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60100. };
  60101. _this._engine = _this.getScene().getEngine();
  60102. _this._generateMipMaps = generateMipMaps;
  60103. _this._samplingMode = samplingMode;
  60104. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60105. _this.name = name || _this._getName(src);
  60106. _this.video = _this._getVideo(src);
  60107. if (settings.autoPlay !== undefined) {
  60108. _this.video.autoplay = settings.autoPlay;
  60109. }
  60110. if (settings.loop !== undefined) {
  60111. _this.video.loop = settings.loop;
  60112. }
  60113. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60114. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60115. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60116. _this.video.addEventListener("emptied", _this.reset);
  60117. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60118. _this._createInternalTexture();
  60119. }
  60120. return _this;
  60121. }
  60122. VideoTexture.prototype._getName = function (src) {
  60123. if (src instanceof HTMLVideoElement) {
  60124. return src.currentSrc;
  60125. }
  60126. if (typeof src === "object") {
  60127. return src.toString();
  60128. }
  60129. return src;
  60130. };
  60131. ;
  60132. VideoTexture.prototype._getVideo = function (src) {
  60133. if (src instanceof HTMLVideoElement) {
  60134. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60135. return src;
  60136. }
  60137. var video = document.createElement("video");
  60138. if (typeof src === "string") {
  60139. BABYLON.Tools.SetCorsBehavior(src, video);
  60140. video.src = src;
  60141. }
  60142. else {
  60143. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60144. src.forEach(function (url) {
  60145. var source = document.createElement("source");
  60146. source.src = url;
  60147. video.appendChild(source);
  60148. });
  60149. }
  60150. return video;
  60151. };
  60152. ;
  60153. /**
  60154. * Internal method to initiate `update`.
  60155. */
  60156. VideoTexture.prototype._rebuild = function () {
  60157. this.update();
  60158. };
  60159. /**
  60160. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60161. */
  60162. VideoTexture.prototype.update = function () {
  60163. if (!this.autoUpdateTexture) {
  60164. // Expecting user to call `updateTexture` manually
  60165. return;
  60166. }
  60167. this.updateTexture(true);
  60168. };
  60169. /**
  60170. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60171. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60172. */
  60173. VideoTexture.prototype.updateTexture = function (isVisible) {
  60174. if (!isVisible) {
  60175. return;
  60176. }
  60177. if (this.video.paused) {
  60178. return;
  60179. }
  60180. this._updateInternalTexture();
  60181. };
  60182. /**
  60183. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60184. * @param url New url.
  60185. */
  60186. VideoTexture.prototype.updateURL = function (url) {
  60187. this.video.src = url;
  60188. };
  60189. VideoTexture.prototype.dispose = function () {
  60190. _super.prototype.dispose.call(this);
  60191. this.video.removeEventListener("canplay", this._createInternalTexture);
  60192. this.video.removeEventListener("paused", this._updateInternalTexture);
  60193. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60194. this.video.removeEventListener("emptied", this.reset);
  60195. this.video.pause();
  60196. };
  60197. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60198. var video = document.createElement("video");
  60199. var constraintsDeviceId;
  60200. if (constraints && constraints.deviceId) {
  60201. constraintsDeviceId = {
  60202. exact: constraints.deviceId,
  60203. };
  60204. }
  60205. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60206. if (navigator.mediaDevices) {
  60207. navigator.mediaDevices.getUserMedia({ video: constraints })
  60208. .then(function (stream) {
  60209. if (video.mozSrcObject !== undefined) {
  60210. // hack for Firefox < 19
  60211. video.mozSrcObject = stream;
  60212. }
  60213. else {
  60214. video.srcObject = stream;
  60215. }
  60216. var onPlaying = function () {
  60217. if (onReady) {
  60218. onReady(new VideoTexture("video", video, scene, true, true));
  60219. }
  60220. video.removeEventListener("playing", onPlaying);
  60221. };
  60222. video.addEventListener("playing", onPlaying);
  60223. video.play();
  60224. })
  60225. .catch(function (err) {
  60226. BABYLON.Tools.Error(err.name);
  60227. });
  60228. }
  60229. else {
  60230. navigator.getUserMedia =
  60231. navigator.getUserMedia ||
  60232. navigator.webkitGetUserMedia ||
  60233. navigator.mozGetUserMedia ||
  60234. navigator.msGetUserMedia;
  60235. if (navigator.getUserMedia) {
  60236. navigator.getUserMedia({
  60237. video: {
  60238. deviceId: constraintsDeviceId,
  60239. width: {
  60240. min: (constraints && constraints.minWidth) || 256,
  60241. max: (constraints && constraints.maxWidth) || 640,
  60242. },
  60243. height: {
  60244. min: (constraints && constraints.minHeight) || 256,
  60245. max: (constraints && constraints.maxHeight) || 480,
  60246. },
  60247. },
  60248. }, function (stream) {
  60249. if (video.mozSrcObject !== undefined) {
  60250. // hack for Firefox < 19
  60251. video.mozSrcObject = stream;
  60252. }
  60253. else {
  60254. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60255. }
  60256. video.play();
  60257. if (onReady) {
  60258. onReady(new VideoTexture("video", video, scene, true, true));
  60259. }
  60260. }, function (e) {
  60261. BABYLON.Tools.Error(e.name);
  60262. });
  60263. }
  60264. }
  60265. };
  60266. return VideoTexture;
  60267. }(BABYLON.Texture));
  60268. BABYLON.VideoTexture = VideoTexture;
  60269. })(BABYLON || (BABYLON = {}));
  60270. //# sourceMappingURL=babylon.videoTexture.js.map
  60271. "use strict";
  60272. var BABYLON;
  60273. (function (BABYLON) {
  60274. var RawTexture = /** @class */ (function (_super) {
  60275. __extends(RawTexture, _super);
  60276. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60277. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60278. if (invertY === void 0) { invertY = false; }
  60279. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60280. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60281. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60282. _this.format = format;
  60283. _this._engine = scene.getEngine();
  60284. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60285. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60286. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60287. return _this;
  60288. }
  60289. RawTexture.prototype.update = function (data) {
  60290. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60291. };
  60292. // Statics
  60293. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60294. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60295. if (invertY === void 0) { invertY = false; }
  60296. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60297. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60298. };
  60299. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60300. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60301. if (invertY === void 0) { invertY = false; }
  60302. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60303. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60304. };
  60305. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60306. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60307. if (invertY === void 0) { invertY = false; }
  60308. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60309. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60310. };
  60311. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60312. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60313. if (invertY === void 0) { invertY = false; }
  60314. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60315. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60316. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60317. };
  60318. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60319. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60320. if (invertY === void 0) { invertY = false; }
  60321. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60322. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60323. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60324. };
  60325. return RawTexture;
  60326. }(BABYLON.Texture));
  60327. BABYLON.RawTexture = RawTexture;
  60328. })(BABYLON || (BABYLON = {}));
  60329. //# sourceMappingURL=babylon.rawTexture.js.map
  60330. "use strict";
  60331. var BABYLON;
  60332. (function (BABYLON) {
  60333. /**
  60334. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60335. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60336. */
  60337. var PostProcess = /** @class */ (function () {
  60338. /**
  60339. * Creates a new instance of @see PostProcess
  60340. * @param name The name of the PostProcess.
  60341. * @param fragmentUrl The url of the fragment shader to be used.
  60342. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60343. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60344. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60345. * @param camera The camera to apply the render pass to.
  60346. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60347. * @param engine The engine which the post process will be applied. (default: current engine)
  60348. * @param reusable If the post process can be reused on the same frame. (default: false)
  60349. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60350. * @param textureType Type of textures used when performing the post process. (default: 0)
  60351. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60352. * @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
  60353. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60354. */
  60355. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60356. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60357. if (defines === void 0) { defines = null; }
  60358. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60359. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60360. if (blockCompilation === void 0) { blockCompilation = false; }
  60361. this.name = name;
  60362. /**
  60363. * Width of the texture to apply the post process on
  60364. */
  60365. this.width = -1;
  60366. /**
  60367. * Height of the texture to apply the post process on
  60368. */
  60369. this.height = -1;
  60370. /**
  60371. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60372. */
  60373. this._outputTexture = null;
  60374. /**
  60375. * If the buffer needs to be cleared before applying the post process. (default: true)
  60376. * Should be set to false if shader will overwrite all previous pixels.
  60377. */
  60378. this.autoClear = true;
  60379. /**
  60380. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60381. */
  60382. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60383. /**
  60384. * Animations to be used for the post processing
  60385. */
  60386. this.animations = new Array();
  60387. /**
  60388. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60389. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60390. */
  60391. this.enablePixelPerfectMode = false;
  60392. /**
  60393. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60394. */
  60395. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60396. /**
  60397. * Force textures to be a power of two (default: false)
  60398. */
  60399. this.alwaysForcePOT = false;
  60400. /**
  60401. * Number of sample textures (default: 1)
  60402. */
  60403. this.samples = 1;
  60404. /**
  60405. * Modify the scale of the post process to be the same as the viewport (default: false)
  60406. */
  60407. this.adaptScaleToCurrentViewport = false;
  60408. this._reusable = false;
  60409. /**
  60410. * Smart array of input and output textures for the post process.
  60411. */
  60412. this._textures = new BABYLON.SmartArray(2);
  60413. /**
  60414. * The index in _textures that corresponds to the output texture.
  60415. */
  60416. this._currentRenderTextureInd = 0;
  60417. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60418. this._texelSize = BABYLON.Vector2.Zero();
  60419. // Events
  60420. /**
  60421. * An event triggered when the postprocess is activated.
  60422. * @type {BABYLON.Observable}
  60423. */
  60424. this.onActivateObservable = new BABYLON.Observable();
  60425. /**
  60426. * An event triggered when the postprocess changes its size.
  60427. * @type {BABYLON.Observable}
  60428. */
  60429. this.onSizeChangedObservable = new BABYLON.Observable();
  60430. /**
  60431. * An event triggered when the postprocess applies its effect.
  60432. * @type {BABYLON.Observable}
  60433. */
  60434. this.onApplyObservable = new BABYLON.Observable();
  60435. /**
  60436. * An event triggered before rendering the postprocess
  60437. * @type {BABYLON.Observable}
  60438. */
  60439. this.onBeforeRenderObservable = new BABYLON.Observable();
  60440. /**
  60441. * An event triggered after rendering the postprocess
  60442. * @type {BABYLON.Observable}
  60443. */
  60444. this.onAfterRenderObservable = new BABYLON.Observable();
  60445. if (camera != null) {
  60446. this._camera = camera;
  60447. this._scene = camera.getScene();
  60448. camera.attachPostProcess(this);
  60449. this._engine = this._scene.getEngine();
  60450. this._scene.postProcesses.push(this);
  60451. }
  60452. else if (engine) {
  60453. this._engine = engine;
  60454. this._engine.postProcesses.push(this);
  60455. }
  60456. this._options = options;
  60457. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60458. this._reusable = reusable || false;
  60459. this._textureType = textureType;
  60460. this._samplers = samplers || [];
  60461. this._samplers.push("textureSampler");
  60462. this._fragmentUrl = fragmentUrl;
  60463. this._vertexUrl = vertexUrl;
  60464. this._parameters = parameters || [];
  60465. this._parameters.push("scale");
  60466. this._indexParameters = indexParameters;
  60467. if (!blockCompilation) {
  60468. this.updateEffect(defines);
  60469. }
  60470. }
  60471. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60472. /**
  60473. * A function that is added to the onActivateObservable
  60474. */
  60475. set: function (callback) {
  60476. if (this._onActivateObserver) {
  60477. this.onActivateObservable.remove(this._onActivateObserver);
  60478. }
  60479. if (callback) {
  60480. this._onActivateObserver = this.onActivateObservable.add(callback);
  60481. }
  60482. },
  60483. enumerable: true,
  60484. configurable: true
  60485. });
  60486. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60487. /**
  60488. * A function that is added to the onSizeChangedObservable
  60489. */
  60490. set: function (callback) {
  60491. if (this._onSizeChangedObserver) {
  60492. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60493. }
  60494. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60495. },
  60496. enumerable: true,
  60497. configurable: true
  60498. });
  60499. Object.defineProperty(PostProcess.prototype, "onApply", {
  60500. /**
  60501. * A function that is added to the onApplyObservable
  60502. */
  60503. set: function (callback) {
  60504. if (this._onApplyObserver) {
  60505. this.onApplyObservable.remove(this._onApplyObserver);
  60506. }
  60507. this._onApplyObserver = this.onApplyObservable.add(callback);
  60508. },
  60509. enumerable: true,
  60510. configurable: true
  60511. });
  60512. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60513. /**
  60514. * A function that is added to the onBeforeRenderObservable
  60515. */
  60516. set: function (callback) {
  60517. if (this._onBeforeRenderObserver) {
  60518. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60519. }
  60520. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60521. },
  60522. enumerable: true,
  60523. configurable: true
  60524. });
  60525. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60526. /**
  60527. * A function that is added to the onAfterRenderObservable
  60528. */
  60529. set: function (callback) {
  60530. if (this._onAfterRenderObserver) {
  60531. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60532. }
  60533. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60534. },
  60535. enumerable: true,
  60536. configurable: true
  60537. });
  60538. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60539. /**
  60540. * 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
  60541. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60542. */
  60543. get: function () {
  60544. return this._textures.data[this._currentRenderTextureInd];
  60545. },
  60546. set: function (value) {
  60547. this._forcedOutputTexture = value;
  60548. },
  60549. enumerable: true,
  60550. configurable: true
  60551. });
  60552. /**
  60553. * Gets the camera which post process is applied to.
  60554. * @returns The camera the post process is applied to.
  60555. */
  60556. PostProcess.prototype.getCamera = function () {
  60557. return this._camera;
  60558. };
  60559. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60560. /**
  60561. * Gets the texel size of the postprocess.
  60562. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60563. */
  60564. get: function () {
  60565. if (this._shareOutputWithPostProcess) {
  60566. return this._shareOutputWithPostProcess.texelSize;
  60567. }
  60568. if (this._forcedOutputTexture) {
  60569. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60570. }
  60571. return this._texelSize;
  60572. },
  60573. enumerable: true,
  60574. configurable: true
  60575. });
  60576. /**
  60577. * Gets the engine which this post process belongs to.
  60578. * @returns The engine the post process was enabled with.
  60579. */
  60580. PostProcess.prototype.getEngine = function () {
  60581. return this._engine;
  60582. };
  60583. /**
  60584. * The effect that is created when initializing the post process.
  60585. * @returns The created effect corrisponding the the postprocess.
  60586. */
  60587. PostProcess.prototype.getEffect = function () {
  60588. return this._effect;
  60589. };
  60590. /**
  60591. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60592. * @param postProcess The post process to share the output with.
  60593. * @returns This post process.
  60594. */
  60595. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60596. this._disposeTextures();
  60597. this._shareOutputWithPostProcess = postProcess;
  60598. return this;
  60599. };
  60600. /**
  60601. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60602. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60603. */
  60604. PostProcess.prototype.useOwnOutput = function () {
  60605. if (this._textures.length == 0) {
  60606. this._textures = new BABYLON.SmartArray(2);
  60607. }
  60608. this._shareOutputWithPostProcess = null;
  60609. };
  60610. /**
  60611. * Updates the effect with the current post process compile time values and recompiles the shader.
  60612. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60613. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60614. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60615. * @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
  60616. * @param onCompiled Called when the shader has been compiled.
  60617. * @param onError Called if there is an error when compiling a shader.
  60618. */
  60619. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60620. if (defines === void 0) { defines = null; }
  60621. if (uniforms === void 0) { uniforms = null; }
  60622. if (samplers === void 0) { samplers = null; }
  60623. 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);
  60624. };
  60625. /**
  60626. * The post process is reusable if it can be used multiple times within one frame.
  60627. * @returns If the post process is reusable
  60628. */
  60629. PostProcess.prototype.isReusable = function () {
  60630. return this._reusable;
  60631. };
  60632. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60633. PostProcess.prototype.markTextureDirty = function () {
  60634. this.width = -1;
  60635. };
  60636. /**
  60637. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60638. * 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.
  60639. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60640. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60641. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60642. * @returns The target texture that was bound to be written to.
  60643. */
  60644. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60645. var _this = this;
  60646. if (sourceTexture === void 0) { sourceTexture = null; }
  60647. camera = camera || this._camera;
  60648. var scene = camera.getScene();
  60649. var engine = scene.getEngine();
  60650. var maxSize = engine.getCaps().maxTextureSize;
  60651. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60652. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60653. // 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
  60654. var webVRCamera = camera.parent;
  60655. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60656. requiredWidth /= 2;
  60657. }
  60658. var desiredWidth = (this._options.width || requiredWidth);
  60659. var desiredHeight = this._options.height || requiredHeight;
  60660. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60661. if (this.adaptScaleToCurrentViewport) {
  60662. var currentViewport = engine.currentViewport;
  60663. if (currentViewport) {
  60664. desiredWidth *= currentViewport.width;
  60665. desiredHeight *= currentViewport.height;
  60666. }
  60667. }
  60668. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60669. if (!this._options.width) {
  60670. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60671. }
  60672. if (!this._options.height) {
  60673. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60674. }
  60675. }
  60676. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60677. if (this._textures.length > 0) {
  60678. for (var i = 0; i < this._textures.length; i++) {
  60679. this._engine._releaseTexture(this._textures.data[i]);
  60680. }
  60681. this._textures.reset();
  60682. }
  60683. this.width = desiredWidth;
  60684. this.height = desiredHeight;
  60685. var textureSize = { width: this.width, height: this.height };
  60686. var textureOptions = {
  60687. generateMipMaps: false,
  60688. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60689. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60690. samplingMode: this.renderTargetSamplingMode,
  60691. type: this._textureType
  60692. };
  60693. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60694. if (this._reusable) {
  60695. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60696. }
  60697. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60698. this.onSizeChangedObservable.notifyObservers(this);
  60699. }
  60700. this._textures.forEach(function (texture) {
  60701. if (texture.samples !== _this.samples) {
  60702. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60703. }
  60704. });
  60705. }
  60706. var target;
  60707. if (this._shareOutputWithPostProcess) {
  60708. target = this._shareOutputWithPostProcess.inputTexture;
  60709. }
  60710. else if (this._forcedOutputTexture) {
  60711. target = this._forcedOutputTexture;
  60712. this.width = this._forcedOutputTexture.width;
  60713. this.height = this._forcedOutputTexture.height;
  60714. }
  60715. else {
  60716. target = this.inputTexture;
  60717. }
  60718. // Bind the input of this post process to be used as the output of the previous post process.
  60719. if (this.enablePixelPerfectMode) {
  60720. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60721. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60722. }
  60723. else {
  60724. this._scaleRatio.copyFromFloats(1, 1);
  60725. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60726. }
  60727. this.onActivateObservable.notifyObservers(camera);
  60728. // Clear
  60729. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60730. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60731. }
  60732. if (this._reusable) {
  60733. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60734. }
  60735. return target;
  60736. };
  60737. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60738. /**
  60739. * If the post process is supported.
  60740. */
  60741. get: function () {
  60742. return this._effect.isSupported;
  60743. },
  60744. enumerable: true,
  60745. configurable: true
  60746. });
  60747. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60748. /**
  60749. * The aspect ratio of the output texture.
  60750. */
  60751. get: function () {
  60752. if (this._shareOutputWithPostProcess) {
  60753. return this._shareOutputWithPostProcess.aspectRatio;
  60754. }
  60755. if (this._forcedOutputTexture) {
  60756. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60757. }
  60758. return this.width / this.height;
  60759. },
  60760. enumerable: true,
  60761. configurable: true
  60762. });
  60763. /**
  60764. * Get a value indicating if the post-process is ready to be used
  60765. * @returns true if the post-process is ready (shader is compiled)
  60766. */
  60767. PostProcess.prototype.isReady = function () {
  60768. return this._effect && this._effect.isReady();
  60769. };
  60770. /**
  60771. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60772. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60773. */
  60774. PostProcess.prototype.apply = function () {
  60775. // Check
  60776. if (!this._effect || !this._effect.isReady())
  60777. return null;
  60778. // States
  60779. this._engine.enableEffect(this._effect);
  60780. this._engine.setState(false);
  60781. this._engine.setDepthBuffer(false);
  60782. this._engine.setDepthWrite(false);
  60783. // Alpha
  60784. this._engine.setAlphaMode(this.alphaMode);
  60785. if (this.alphaConstants) {
  60786. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60787. }
  60788. // Bind the output texture of the preivous post process as the input to this post process.
  60789. var source;
  60790. if (this._shareOutputWithPostProcess) {
  60791. source = this._shareOutputWithPostProcess.inputTexture;
  60792. }
  60793. else if (this._forcedOutputTexture) {
  60794. source = this._forcedOutputTexture;
  60795. }
  60796. else {
  60797. source = this.inputTexture;
  60798. }
  60799. this._effect._bindTexture("textureSampler", source);
  60800. // Parameters
  60801. this._effect.setVector2("scale", this._scaleRatio);
  60802. this.onApplyObservable.notifyObservers(this._effect);
  60803. return this._effect;
  60804. };
  60805. PostProcess.prototype._disposeTextures = function () {
  60806. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60807. return;
  60808. }
  60809. if (this._textures.length > 0) {
  60810. for (var i = 0; i < this._textures.length; i++) {
  60811. this._engine._releaseTexture(this._textures.data[i]);
  60812. }
  60813. }
  60814. this._textures.dispose();
  60815. };
  60816. /**
  60817. * Disposes the post process.
  60818. * @param camera The camera to dispose the post process on.
  60819. */
  60820. PostProcess.prototype.dispose = function (camera) {
  60821. camera = camera || this._camera;
  60822. this._disposeTextures();
  60823. if (this._scene) {
  60824. var index_1 = this._scene.postProcesses.indexOf(this);
  60825. if (index_1 !== -1) {
  60826. this._scene.postProcesses.splice(index_1, 1);
  60827. }
  60828. }
  60829. else {
  60830. var index_2 = this._engine.postProcesses.indexOf(this);
  60831. if (index_2 !== -1) {
  60832. this._engine.postProcesses.splice(index_2, 1);
  60833. }
  60834. }
  60835. if (!camera) {
  60836. return;
  60837. }
  60838. camera.detachPostProcess(this);
  60839. var index = camera._postProcesses.indexOf(this);
  60840. if (index === 0 && camera._postProcesses.length > 0) {
  60841. var firstPostProcess = this._camera._getFirstPostProcess();
  60842. if (firstPostProcess) {
  60843. firstPostProcess.markTextureDirty();
  60844. }
  60845. }
  60846. this.onActivateObservable.clear();
  60847. this.onAfterRenderObservable.clear();
  60848. this.onApplyObservable.clear();
  60849. this.onBeforeRenderObservable.clear();
  60850. this.onSizeChangedObservable.clear();
  60851. };
  60852. return PostProcess;
  60853. }());
  60854. BABYLON.PostProcess = PostProcess;
  60855. })(BABYLON || (BABYLON = {}));
  60856. //# sourceMappingURL=babylon.postProcess.js.map
  60857. "use strict";
  60858. var BABYLON;
  60859. (function (BABYLON) {
  60860. var PassPostProcess = /** @class */ (function (_super) {
  60861. __extends(PassPostProcess, _super);
  60862. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60863. if (camera === void 0) { camera = null; }
  60864. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60865. if (blockCompilation === void 0) { blockCompilation = false; }
  60866. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60867. }
  60868. return PassPostProcess;
  60869. }(BABYLON.PostProcess));
  60870. BABYLON.PassPostProcess = PassPostProcess;
  60871. })(BABYLON || (BABYLON = {}));
  60872. //# sourceMappingURL=babylon.passPostProcess.js.map
  60873. "use strict";
  60874. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60875. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60876. s = arguments[i];
  60877. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60878. t[p] = s[p];
  60879. }
  60880. return t;
  60881. };
  60882. var BABYLON;
  60883. (function (BABYLON) {
  60884. /**
  60885. * Default implementation of @see IShadowGenerator.
  60886. * This is the main object responsible of generating shadows in the framework.
  60887. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60888. */
  60889. var ShadowGenerator = /** @class */ (function () {
  60890. /**
  60891. * Creates a ShadowGenerator object.
  60892. * A ShadowGenerator is the required tool to use the shadows.
  60893. * Each light casting shadows needs to use its own ShadowGenerator.
  60894. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60895. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60896. * @param light The light object generating the shadows.
  60897. * @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.
  60898. */
  60899. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60900. this._bias = 0.00005;
  60901. this._normalBias = 0;
  60902. this._blurBoxOffset = 1;
  60903. this._blurScale = 2;
  60904. this._blurKernel = 1;
  60905. this._useKernelBlur = false;
  60906. this._filter = ShadowGenerator.FILTER_NONE;
  60907. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  60908. this._contactHardeningLightSizeUVRatio = 0.1;
  60909. this._darkness = 0;
  60910. this._transparencyShadow = false;
  60911. /**
  60912. * Controls the extent to which the shadows fade out at the edge of the frustum
  60913. * Used only by directionals and spots
  60914. */
  60915. this.frustumEdgeFalloff = 0;
  60916. /**
  60917. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60918. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60919. * It might on the other hand introduce peter panning.
  60920. */
  60921. this.forceBackFacesOnly = false;
  60922. this._lightDirection = BABYLON.Vector3.Zero();
  60923. this._viewMatrix = BABYLON.Matrix.Zero();
  60924. this._projectionMatrix = BABYLON.Matrix.Zero();
  60925. this._transformMatrix = BABYLON.Matrix.Zero();
  60926. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60927. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60928. this._currentFaceIndex = 0;
  60929. this._currentFaceIndexCache = 0;
  60930. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60931. this._mapSize = mapSize;
  60932. this._light = light;
  60933. this._scene = light.getScene();
  60934. light._shadowGenerator = this;
  60935. // Texture type fallback from float to int if not supported.
  60936. var caps = this._scene.getEngine().getCaps();
  60937. if (!useFullFloatFirst) {
  60938. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60939. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60940. }
  60941. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60942. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60943. }
  60944. else {
  60945. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60946. }
  60947. }
  60948. else {
  60949. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60950. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60951. }
  60952. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60953. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60954. }
  60955. else {
  60956. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60957. }
  60958. }
  60959. this._initializeGenerator();
  60960. this._applyFilterValues();
  60961. }
  60962. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60963. /**
  60964. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  60965. */
  60966. get: function () {
  60967. return this._bias;
  60968. },
  60969. /**
  60970. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  60971. */
  60972. set: function (bias) {
  60973. this._bias = bias;
  60974. },
  60975. enumerable: true,
  60976. configurable: true
  60977. });
  60978. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  60979. /**
  60980. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60981. */
  60982. get: function () {
  60983. return this._normalBias;
  60984. },
  60985. /**
  60986. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60987. */
  60988. set: function (normalBias) {
  60989. this._normalBias = normalBias;
  60990. },
  60991. enumerable: true,
  60992. configurable: true
  60993. });
  60994. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60995. /**
  60996. * Gets the blur box offset: offset applied during the blur pass.
  60997. * Only usefull if useKernelBlur = false
  60998. */
  60999. get: function () {
  61000. return this._blurBoxOffset;
  61001. },
  61002. /**
  61003. * Sets the blur box offset: offset applied during the blur pass.
  61004. * Only usefull if useKernelBlur = false
  61005. */
  61006. set: function (value) {
  61007. if (this._blurBoxOffset === value) {
  61008. return;
  61009. }
  61010. this._blurBoxOffset = value;
  61011. this._disposeBlurPostProcesses();
  61012. },
  61013. enumerable: true,
  61014. configurable: true
  61015. });
  61016. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  61017. /**
  61018. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  61019. * 2 means half of the size.
  61020. */
  61021. get: function () {
  61022. return this._blurScale;
  61023. },
  61024. /**
  61025. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  61026. * 2 means half of the size.
  61027. */
  61028. set: function (value) {
  61029. if (this._blurScale === value) {
  61030. return;
  61031. }
  61032. this._blurScale = value;
  61033. this._disposeBlurPostProcesses();
  61034. },
  61035. enumerable: true,
  61036. configurable: true
  61037. });
  61038. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61039. /**
  61040. * Gets the blur kernel: kernel size of the blur pass.
  61041. * Only usefull if useKernelBlur = true
  61042. */
  61043. get: function () {
  61044. return this._blurKernel;
  61045. },
  61046. /**
  61047. * Sets the blur kernel: kernel size of the blur pass.
  61048. * Only usefull if useKernelBlur = true
  61049. */
  61050. set: function (value) {
  61051. if (this._blurKernel === value) {
  61052. return;
  61053. }
  61054. this._blurKernel = value;
  61055. this._disposeBlurPostProcesses();
  61056. },
  61057. enumerable: true,
  61058. configurable: true
  61059. });
  61060. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61061. /**
  61062. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61063. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61064. */
  61065. get: function () {
  61066. return this._useKernelBlur;
  61067. },
  61068. /**
  61069. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61070. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61071. */
  61072. set: function (value) {
  61073. if (this._useKernelBlur === value) {
  61074. return;
  61075. }
  61076. this._useKernelBlur = value;
  61077. this._disposeBlurPostProcesses();
  61078. },
  61079. enumerable: true,
  61080. configurable: true
  61081. });
  61082. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61083. /**
  61084. * Gets the depth scale used in ESM mode.
  61085. */
  61086. get: function () {
  61087. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61088. },
  61089. /**
  61090. * Sets the depth scale used in ESM mode.
  61091. * This can override the scale stored on the light.
  61092. */
  61093. set: function (value) {
  61094. this._depthScale = value;
  61095. },
  61096. enumerable: true,
  61097. configurable: true
  61098. });
  61099. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61100. /**
  61101. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61102. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61103. */
  61104. get: function () {
  61105. return this._filter;
  61106. },
  61107. /**
  61108. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61109. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61110. */
  61111. set: function (value) {
  61112. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61113. if (this._light.needCube()) {
  61114. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61115. this.useExponentialShadowMap = true;
  61116. return;
  61117. }
  61118. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61119. this.useCloseExponentialShadowMap = true;
  61120. return;
  61121. }
  61122. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61123. this.usePoissonSampling = true;
  61124. return;
  61125. }
  61126. }
  61127. // Weblg1 fallback for PCF.
  61128. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61129. if (this._scene.getEngine().webGLVersion === 1) {
  61130. this.usePoissonSampling = true;
  61131. return;
  61132. }
  61133. }
  61134. if (this._filter === value) {
  61135. return;
  61136. }
  61137. this._filter = value;
  61138. this._disposeBlurPostProcesses();
  61139. this._applyFilterValues();
  61140. this._light._markMeshesAsLightDirty();
  61141. },
  61142. enumerable: true,
  61143. configurable: true
  61144. });
  61145. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61146. /**
  61147. * Gets if the current filter is set to Poisson Sampling.
  61148. */
  61149. get: function () {
  61150. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61151. },
  61152. /**
  61153. * Sets the current filter to Poisson Sampling.
  61154. */
  61155. set: function (value) {
  61156. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61157. return;
  61158. }
  61159. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61160. },
  61161. enumerable: true,
  61162. configurable: true
  61163. });
  61164. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61165. /**
  61166. * Gets if the current filter is set to VSM.
  61167. * DEPRECATED. Should use useExponentialShadowMap instead.
  61168. */
  61169. get: function () {
  61170. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61171. return this.useExponentialShadowMap;
  61172. },
  61173. /**
  61174. * Sets the current filter is to VSM.
  61175. * DEPRECATED. Should use useExponentialShadowMap instead.
  61176. */
  61177. set: function (value) {
  61178. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61179. this.useExponentialShadowMap = value;
  61180. },
  61181. enumerable: true,
  61182. configurable: true
  61183. });
  61184. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61185. /**
  61186. * Gets if the current filter is set to blurred VSM.
  61187. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61188. */
  61189. get: function () {
  61190. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61191. return this.useBlurExponentialShadowMap;
  61192. },
  61193. /**
  61194. * Sets the current filter is to blurred VSM.
  61195. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61196. */
  61197. set: function (value) {
  61198. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61199. this.useBlurExponentialShadowMap = value;
  61200. },
  61201. enumerable: true,
  61202. configurable: true
  61203. });
  61204. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61205. /**
  61206. * Gets if the current filter is set to ESM.
  61207. */
  61208. get: function () {
  61209. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61210. },
  61211. /**
  61212. * Sets the current filter is to ESM.
  61213. */
  61214. set: function (value) {
  61215. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61216. return;
  61217. }
  61218. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61219. },
  61220. enumerable: true,
  61221. configurable: true
  61222. });
  61223. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61224. /**
  61225. * Gets if the current filter is set to filtered ESM.
  61226. */
  61227. get: function () {
  61228. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61229. },
  61230. /**
  61231. * Gets if the current filter is set to filtered ESM.
  61232. */
  61233. set: function (value) {
  61234. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61235. return;
  61236. }
  61237. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61238. },
  61239. enumerable: true,
  61240. configurable: true
  61241. });
  61242. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61243. /**
  61244. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61245. * exponential to prevent steep falloff artifacts).
  61246. */
  61247. get: function () {
  61248. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61249. },
  61250. /**
  61251. * Sets the current filter to "close ESM" (using the inverse of the
  61252. * exponential to prevent steep falloff artifacts).
  61253. */
  61254. set: function (value) {
  61255. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61256. return;
  61257. }
  61258. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61259. },
  61260. enumerable: true,
  61261. configurable: true
  61262. });
  61263. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61264. /**
  61265. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61266. * exponential to prevent steep falloff artifacts).
  61267. */
  61268. get: function () {
  61269. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61270. },
  61271. /**
  61272. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61273. * exponential to prevent steep falloff artifacts).
  61274. */
  61275. set: function (value) {
  61276. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61277. return;
  61278. }
  61279. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61280. },
  61281. enumerable: true,
  61282. configurable: true
  61283. });
  61284. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61285. /**
  61286. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61287. */
  61288. get: function () {
  61289. return this.filter === ShadowGenerator.FILTER_PCF;
  61290. },
  61291. /**
  61292. * Sets the current filter to "PCF" (percentage closer filtering).
  61293. */
  61294. set: function (value) {
  61295. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61296. return;
  61297. }
  61298. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61299. },
  61300. enumerable: true,
  61301. configurable: true
  61302. });
  61303. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61304. /**
  61305. * Gets the PCF or PCSS Quality.
  61306. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61307. */
  61308. get: function () {
  61309. return this._filteringQuality;
  61310. },
  61311. /**
  61312. * Sets the PCF or PCSS Quality.
  61313. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61314. */
  61315. set: function (filteringQuality) {
  61316. this._filteringQuality = filteringQuality;
  61317. },
  61318. enumerable: true,
  61319. configurable: true
  61320. });
  61321. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61322. /**
  61323. * Gets if the current filter is set to "PCSS" (contact hardening).
  61324. */
  61325. get: function () {
  61326. return this.filter === ShadowGenerator.FILTER_PCSS;
  61327. },
  61328. /**
  61329. * Sets the current filter to "PCSS" (contact hardening).
  61330. */
  61331. set: function (value) {
  61332. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61333. return;
  61334. }
  61335. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61336. },
  61337. enumerable: true,
  61338. configurable: true
  61339. });
  61340. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61341. /**
  61342. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61343. * Using a ratio helps keeping shape stability independently of the map size.
  61344. *
  61345. * It does not account for the light projection as it was having too much
  61346. * instability during the light setup or during light position changes.
  61347. *
  61348. * Only valid if useContactHardeningShadow is true.
  61349. */
  61350. get: function () {
  61351. return this._contactHardeningLightSizeUVRatio;
  61352. },
  61353. /**
  61354. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61355. * Using a ratio helps keeping shape stability independently of the map size.
  61356. *
  61357. * It does not account for the light projection as it was having too much
  61358. * instability during the light setup or during light position changes.
  61359. *
  61360. * Only valid if useContactHardeningShadow is true.
  61361. */
  61362. set: function (contactHardeningLightSizeUVRatio) {
  61363. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61364. },
  61365. enumerable: true,
  61366. configurable: true
  61367. });
  61368. /**
  61369. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61370. * 0 means strongest and 1 would means no shadow.
  61371. * @returns the darkness.
  61372. */
  61373. ShadowGenerator.prototype.getDarkness = function () {
  61374. return this._darkness;
  61375. };
  61376. /**
  61377. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61378. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61379. * @returns the shadow generator allowing fluent coding.
  61380. */
  61381. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61382. if (darkness >= 1.0)
  61383. this._darkness = 1.0;
  61384. else if (darkness <= 0.0)
  61385. this._darkness = 0.0;
  61386. else
  61387. this._darkness = darkness;
  61388. return this;
  61389. };
  61390. /**
  61391. * Sets the ability to have transparent shadow (boolean).
  61392. * @param transparent True if transparent else False
  61393. * @returns the shadow generator allowing fluent coding
  61394. */
  61395. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61396. this._transparencyShadow = transparent;
  61397. return this;
  61398. };
  61399. /**
  61400. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61401. * @returns The render target texture if present otherwise, null
  61402. */
  61403. ShadowGenerator.prototype.getShadowMap = function () {
  61404. return this._shadowMap;
  61405. };
  61406. /**
  61407. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61408. * @returns The render target texture if the shadow map is present otherwise, null
  61409. */
  61410. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61411. if (this._shadowMap2) {
  61412. return this._shadowMap2;
  61413. }
  61414. return this._shadowMap;
  61415. };
  61416. /**
  61417. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61418. * @param mesh Mesh to add
  61419. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61420. * @returns the Shadow Generator itself
  61421. */
  61422. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61423. if (includeDescendants === void 0) { includeDescendants = true; }
  61424. if (!this._shadowMap) {
  61425. return this;
  61426. }
  61427. if (!this._shadowMap.renderList) {
  61428. this._shadowMap.renderList = [];
  61429. }
  61430. this._shadowMap.renderList.push(mesh);
  61431. if (includeDescendants) {
  61432. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61433. }
  61434. return this;
  61435. var _a;
  61436. };
  61437. /**
  61438. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61439. * @param mesh Mesh to remove
  61440. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61441. * @returns the Shadow Generator itself
  61442. */
  61443. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61444. if (includeDescendants === void 0) { includeDescendants = true; }
  61445. if (!this._shadowMap || !this._shadowMap.renderList) {
  61446. return this;
  61447. }
  61448. var index = this._shadowMap.renderList.indexOf(mesh);
  61449. if (index !== -1) {
  61450. this._shadowMap.renderList.splice(index, 1);
  61451. }
  61452. if (includeDescendants) {
  61453. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61454. var child = _a[_i];
  61455. this.removeShadowCaster(child);
  61456. }
  61457. }
  61458. return this;
  61459. };
  61460. /**
  61461. * Returns the associated light object.
  61462. * @returns the light generating the shadow
  61463. */
  61464. ShadowGenerator.prototype.getLight = function () {
  61465. return this._light;
  61466. };
  61467. ShadowGenerator.prototype._initializeGenerator = function () {
  61468. this._light._markMeshesAsLightDirty();
  61469. this._initializeShadowMap();
  61470. };
  61471. ShadowGenerator.prototype._initializeShadowMap = function () {
  61472. var _this = this;
  61473. // Render target
  61474. var engine = this._scene.getEngine();
  61475. if (engine.webGLVersion > 1) {
  61476. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61477. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61478. }
  61479. else {
  61480. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61481. }
  61482. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61483. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61484. this._shadowMap.anisotropicFilteringLevel = 1;
  61485. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61486. this._shadowMap.renderParticles = false;
  61487. this._shadowMap.ignoreCameraViewport = true;
  61488. // Record Face Index before render.
  61489. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61490. _this._currentFaceIndex = faceIndex;
  61491. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61492. engine.setColorWrite(false);
  61493. }
  61494. });
  61495. // Custom render function.
  61496. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61497. // Blur if required afer render.
  61498. this._shadowMap.onAfterUnbindObservable.add(function () {
  61499. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61500. engine.setColorWrite(true);
  61501. }
  61502. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61503. return;
  61504. }
  61505. var shadowMap = _this.getShadowMapForRendering();
  61506. if (shadowMap) {
  61507. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61508. }
  61509. });
  61510. // Clear according to the chosen filter.
  61511. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61512. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61513. this._shadowMap.onClearObservable.add(function (engine) {
  61514. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61515. engine.clear(clearOne, false, true, false);
  61516. }
  61517. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61518. engine.clear(clearZero, true, true, false);
  61519. }
  61520. else {
  61521. engine.clear(clearOne, true, true, false);
  61522. }
  61523. });
  61524. };
  61525. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61526. var _this = this;
  61527. var engine = this._scene.getEngine();
  61528. var targetSize = this._mapSize / this.blurScale;
  61529. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61530. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61531. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61532. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61533. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61534. }
  61535. if (this.useKernelBlur) {
  61536. 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);
  61537. this._kernelBlurXPostprocess.width = targetSize;
  61538. this._kernelBlurXPostprocess.height = targetSize;
  61539. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61540. effect.setTexture("textureSampler", _this._shadowMap);
  61541. });
  61542. 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);
  61543. this._kernelBlurXPostprocess.autoClear = false;
  61544. this._kernelBlurYPostprocess.autoClear = false;
  61545. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61546. this._kernelBlurXPostprocess.packedFloat = true;
  61547. this._kernelBlurYPostprocess.packedFloat = true;
  61548. }
  61549. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61550. }
  61551. else {
  61552. 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);
  61553. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61554. effect.setFloat2("screenSize", targetSize, targetSize);
  61555. effect.setTexture("textureSampler", _this._shadowMap);
  61556. });
  61557. this._boxBlurPostprocess.autoClear = false;
  61558. this._blurPostProcesses = [this._boxBlurPostprocess];
  61559. }
  61560. };
  61561. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61562. var index;
  61563. var engine = this._scene.getEngine();
  61564. if (depthOnlySubMeshes.length) {
  61565. engine.setColorWrite(false);
  61566. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61567. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61568. }
  61569. engine.setColorWrite(true);
  61570. }
  61571. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61572. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61573. }
  61574. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61575. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61576. }
  61577. if (this._transparencyShadow) {
  61578. for (index = 0; index < transparentSubMeshes.length; index++) {
  61579. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61580. }
  61581. }
  61582. };
  61583. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61584. var _this = this;
  61585. var mesh = subMesh.getRenderingMesh();
  61586. var scene = this._scene;
  61587. var engine = scene.getEngine();
  61588. var material = subMesh.getMaterial();
  61589. if (!material) {
  61590. return;
  61591. }
  61592. // Culling
  61593. engine.setState(material.backFaceCulling);
  61594. // Managing instances
  61595. var batch = mesh._getInstancesRenderList(subMesh._id);
  61596. if (batch.mustReturn) {
  61597. return;
  61598. }
  61599. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61600. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61601. engine.enableEffect(this._effect);
  61602. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61603. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61604. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61605. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61606. this._effect.setVector3("lightData", this._cachedDirection);
  61607. }
  61608. else {
  61609. this._effect.setVector3("lightData", this._cachedPosition);
  61610. }
  61611. if (scene.activeCamera) {
  61612. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61613. }
  61614. // Alpha test
  61615. if (material && material.needAlphaTesting()) {
  61616. var alphaTexture = material.getAlphaTestTexture();
  61617. if (alphaTexture) {
  61618. this._effect.setTexture("diffuseSampler", alphaTexture);
  61619. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61620. }
  61621. }
  61622. // Bones
  61623. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61624. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61625. }
  61626. // Morph targets
  61627. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  61628. if (this.forceBackFacesOnly) {
  61629. engine.setState(true, 0, false, true);
  61630. }
  61631. // Draw
  61632. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61633. if (this.forceBackFacesOnly) {
  61634. engine.setState(true, 0, false, false);
  61635. }
  61636. }
  61637. else {
  61638. // Need to reset refresh rate of the shadowMap
  61639. if (this._shadowMap) {
  61640. this._shadowMap.resetRefreshCounter();
  61641. }
  61642. }
  61643. };
  61644. ShadowGenerator.prototype._applyFilterValues = function () {
  61645. if (!this._shadowMap) {
  61646. return;
  61647. }
  61648. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61649. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61650. }
  61651. else {
  61652. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61653. }
  61654. };
  61655. /**
  61656. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61657. * @param onCompiled Callback triggered at the and of the effects compilation
  61658. * @param options Sets of optional options forcing the compilation with different modes
  61659. */
  61660. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61661. var _this = this;
  61662. var localOptions = __assign({ useInstances: false }, options);
  61663. var shadowMap = this.getShadowMap();
  61664. if (!shadowMap) {
  61665. if (onCompiled) {
  61666. onCompiled(this);
  61667. }
  61668. return;
  61669. }
  61670. var renderList = shadowMap.renderList;
  61671. if (!renderList) {
  61672. if (onCompiled) {
  61673. onCompiled(this);
  61674. }
  61675. return;
  61676. }
  61677. var subMeshes = new Array();
  61678. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61679. var mesh = renderList_1[_i];
  61680. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61681. }
  61682. if (subMeshes.length === 0) {
  61683. if (onCompiled) {
  61684. onCompiled(this);
  61685. }
  61686. return;
  61687. }
  61688. var currentIndex = 0;
  61689. var checkReady = function () {
  61690. if (!_this._scene || !_this._scene.getEngine()) {
  61691. return;
  61692. }
  61693. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61694. currentIndex++;
  61695. if (currentIndex >= subMeshes.length) {
  61696. if (onCompiled) {
  61697. onCompiled(_this);
  61698. }
  61699. return;
  61700. }
  61701. }
  61702. setTimeout(checkReady, 16);
  61703. };
  61704. checkReady();
  61705. };
  61706. /**
  61707. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61708. * @param options Sets of optional options forcing the compilation with different modes
  61709. * @returns A promise that resolves when the compilation completes
  61710. */
  61711. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61712. var _this = this;
  61713. return new Promise(function (resolve) {
  61714. _this.forceCompilation(function () {
  61715. resolve();
  61716. }, options);
  61717. });
  61718. };
  61719. /**
  61720. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61721. * @param subMesh The submesh we want to render in the shadow map
  61722. * @param useInstances Defines wether will draw in the map using instances
  61723. * @returns true if ready otherwise, false
  61724. */
  61725. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61726. var defines = [];
  61727. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61728. defines.push("#define FLOAT");
  61729. }
  61730. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61731. defines.push("#define ESM");
  61732. }
  61733. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61734. defines.push("#define DEPTHTEXTURE");
  61735. }
  61736. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61737. var mesh = subMesh.getMesh();
  61738. var material = subMesh.getMaterial();
  61739. // Normal bias.
  61740. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61741. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61742. defines.push("#define NORMAL");
  61743. if (mesh.nonUniformScaling) {
  61744. defines.push("#define NONUNIFORMSCALING");
  61745. }
  61746. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61747. defines.push("#define DIRECTIONINLIGHTDATA");
  61748. }
  61749. }
  61750. // Alpha test
  61751. if (material && material.needAlphaTesting()) {
  61752. var alphaTexture = material.getAlphaTestTexture();
  61753. if (alphaTexture) {
  61754. defines.push("#define ALPHATEST");
  61755. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61756. attribs.push(BABYLON.VertexBuffer.UVKind);
  61757. defines.push("#define UV1");
  61758. }
  61759. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61760. if (alphaTexture.coordinatesIndex === 1) {
  61761. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61762. defines.push("#define UV2");
  61763. }
  61764. }
  61765. }
  61766. }
  61767. // Bones
  61768. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61769. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61770. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61771. if (mesh.numBoneInfluencers > 4) {
  61772. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61773. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61774. }
  61775. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61776. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61777. }
  61778. else {
  61779. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61780. }
  61781. // Morph targets
  61782. var manager = mesh.morphTargetManager;
  61783. var morphInfluencers = 0;
  61784. if (manager) {
  61785. if (manager.numInfluencers > 0) {
  61786. defines.push("#define MORPHTARGETS");
  61787. morphInfluencers = manager.numInfluencers;
  61788. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  61789. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  61790. }
  61791. }
  61792. // Instances
  61793. if (useInstances) {
  61794. defines.push("#define INSTANCES");
  61795. attribs.push("world0");
  61796. attribs.push("world1");
  61797. attribs.push("world2");
  61798. attribs.push("world3");
  61799. }
  61800. // Get correct effect
  61801. var join = defines.join("\n");
  61802. if (this._cachedDefines !== join) {
  61803. this._cachedDefines = join;
  61804. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  61805. }
  61806. if (!this._effect.isReady()) {
  61807. return false;
  61808. }
  61809. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61810. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61811. this._initializeBlurRTTAndPostProcesses();
  61812. }
  61813. }
  61814. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61815. return false;
  61816. }
  61817. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61818. return false;
  61819. }
  61820. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61821. return false;
  61822. }
  61823. return true;
  61824. };
  61825. /**
  61826. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61827. * @param defines Defines of the material we want to update
  61828. * @param lightIndex Index of the light in the enabled light list of the material
  61829. */
  61830. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61831. var scene = this._scene;
  61832. var light = this._light;
  61833. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61834. return;
  61835. }
  61836. defines["SHADOW" + lightIndex] = true;
  61837. if (this.useContactHardeningShadow) {
  61838. defines["SHADOWPCSS" + lightIndex] = true;
  61839. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61840. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61841. }
  61842. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61843. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61844. }
  61845. // else default to high.
  61846. }
  61847. if (this.usePercentageCloserFiltering) {
  61848. defines["SHADOWPCF" + lightIndex] = true;
  61849. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61850. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61851. }
  61852. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61853. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61854. }
  61855. // else default to high.
  61856. }
  61857. else if (this.usePoissonSampling) {
  61858. defines["SHADOWPOISSON" + lightIndex] = true;
  61859. }
  61860. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61861. defines["SHADOWESM" + lightIndex] = true;
  61862. }
  61863. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61864. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61865. }
  61866. if (light.needCube()) {
  61867. defines["SHADOWCUBE" + lightIndex] = true;
  61868. }
  61869. };
  61870. /**
  61871. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61872. * defined in the generator but impacting the effect).
  61873. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61874. * @param effect The effect we are binfing the information for
  61875. */
  61876. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61877. var light = this._light;
  61878. var scene = this._scene;
  61879. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61880. return;
  61881. }
  61882. var camera = scene.activeCamera;
  61883. if (!camera) {
  61884. return;
  61885. }
  61886. var shadowMap = this.getShadowMap();
  61887. if (!shadowMap) {
  61888. return;
  61889. }
  61890. if (!light.needCube()) {
  61891. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61892. }
  61893. // Only PCF uses depth stencil texture.
  61894. if (this._filter === ShadowGenerator.FILTER_PCF) {
  61895. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61896. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61897. }
  61898. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  61899. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61900. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  61901. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61902. }
  61903. else {
  61904. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61905. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61906. }
  61907. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61908. };
  61909. /**
  61910. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61911. * (eq to shadow prjection matrix * light transform matrix)
  61912. * @returns The transform matrix used to create the shadow map
  61913. */
  61914. ShadowGenerator.prototype.getTransformMatrix = function () {
  61915. var scene = this._scene;
  61916. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61917. return this._transformMatrix;
  61918. }
  61919. this._currentRenderID = scene.getRenderId();
  61920. this._currentFaceIndexCache = this._currentFaceIndex;
  61921. var lightPosition = this._light.position;
  61922. if (this._light.computeTransformedInformation()) {
  61923. lightPosition = this._light.transformedPosition;
  61924. }
  61925. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61926. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61927. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61928. }
  61929. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61930. this._cachedPosition.copyFrom(lightPosition);
  61931. this._cachedDirection.copyFrom(this._lightDirection);
  61932. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61933. var shadowMap = this.getShadowMap();
  61934. if (shadowMap) {
  61935. var renderList = shadowMap.renderList;
  61936. if (renderList) {
  61937. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61938. }
  61939. }
  61940. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61941. }
  61942. return this._transformMatrix;
  61943. };
  61944. /**
  61945. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61946. * Cube and 2D textures for instance.
  61947. */
  61948. ShadowGenerator.prototype.recreateShadowMap = function () {
  61949. var shadowMap = this._shadowMap;
  61950. if (!shadowMap) {
  61951. return;
  61952. }
  61953. // Track render list.
  61954. var renderList = shadowMap.renderList;
  61955. // Clean up existing data.
  61956. this._disposeRTTandPostProcesses();
  61957. // Reinitializes.
  61958. this._initializeGenerator();
  61959. // Reaffect the filter to ensure a correct fallback if necessary.
  61960. this.filter = this.filter;
  61961. // Reaffect the filter.
  61962. this._applyFilterValues();
  61963. // Reaffect Render List.
  61964. this._shadowMap.renderList = renderList;
  61965. };
  61966. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61967. if (this._shadowMap2) {
  61968. this._shadowMap2.dispose();
  61969. this._shadowMap2 = null;
  61970. }
  61971. if (this._boxBlurPostprocess) {
  61972. this._boxBlurPostprocess.dispose();
  61973. this._boxBlurPostprocess = null;
  61974. }
  61975. if (this._kernelBlurXPostprocess) {
  61976. this._kernelBlurXPostprocess.dispose();
  61977. this._kernelBlurXPostprocess = null;
  61978. }
  61979. if (this._kernelBlurYPostprocess) {
  61980. this._kernelBlurYPostprocess.dispose();
  61981. this._kernelBlurYPostprocess = null;
  61982. }
  61983. this._blurPostProcesses = [];
  61984. };
  61985. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61986. if (this._shadowMap) {
  61987. this._shadowMap.dispose();
  61988. this._shadowMap = null;
  61989. }
  61990. this._disposeBlurPostProcesses();
  61991. };
  61992. /**
  61993. * Disposes the ShadowGenerator.
  61994. * Returns nothing.
  61995. */
  61996. ShadowGenerator.prototype.dispose = function () {
  61997. this._disposeRTTandPostProcesses();
  61998. if (this._light) {
  61999. this._light._shadowGenerator = null;
  62000. this._light._markMeshesAsLightDirty();
  62001. }
  62002. };
  62003. /**
  62004. * Serializes the shadow generator setup to a json object.
  62005. * @returns The serialized JSON object
  62006. */
  62007. ShadowGenerator.prototype.serialize = function () {
  62008. var serializationObject = {};
  62009. var shadowMap = this.getShadowMap();
  62010. if (!shadowMap) {
  62011. return serializationObject;
  62012. }
  62013. serializationObject.lightId = this._light.id;
  62014. serializationObject.mapSize = shadowMap.getRenderSize();
  62015. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  62016. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  62017. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62018. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62019. serializationObject.usePoissonSampling = this.usePoissonSampling;
  62020. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  62021. serializationObject.depthScale = this.depthScale;
  62022. serializationObject.darkness = this.getDarkness();
  62023. serializationObject.blurBoxOffset = this.blurBoxOffset;
  62024. serializationObject.blurKernel = this.blurKernel;
  62025. serializationObject.blurScale = this.blurScale;
  62026. serializationObject.useKernelBlur = this.useKernelBlur;
  62027. serializationObject.transparencyShadow = this._transparencyShadow;
  62028. serializationObject.bias = this.bias;
  62029. serializationObject.normalBias = this.normalBias;
  62030. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  62031. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  62032. serializationObject.filteringQuality = this.filteringQuality;
  62033. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  62034. serializationObject.renderList = [];
  62035. if (shadowMap.renderList) {
  62036. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  62037. var mesh = shadowMap.renderList[meshIndex];
  62038. serializationObject.renderList.push(mesh.id);
  62039. }
  62040. }
  62041. return serializationObject;
  62042. };
  62043. /**
  62044. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  62045. * @param parsedShadowGenerator The JSON object to parse
  62046. * @param scene The scene to create the shadow map for
  62047. * @returns The parsed shadow generator
  62048. */
  62049. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62050. //casting to point light, as light is missing the position attr and typescript complains.
  62051. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62052. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62053. var shadowMap = shadowGenerator.getShadowMap();
  62054. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62055. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62056. meshes.forEach(function (mesh) {
  62057. if (!shadowMap) {
  62058. return;
  62059. }
  62060. if (!shadowMap.renderList) {
  62061. shadowMap.renderList = [];
  62062. }
  62063. shadowMap.renderList.push(mesh);
  62064. });
  62065. }
  62066. if (parsedShadowGenerator.usePoissonSampling) {
  62067. shadowGenerator.usePoissonSampling = true;
  62068. }
  62069. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62070. shadowGenerator.useExponentialShadowMap = true;
  62071. }
  62072. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62073. shadowGenerator.useBlurExponentialShadowMap = true;
  62074. }
  62075. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62076. shadowGenerator.useCloseExponentialShadowMap = true;
  62077. }
  62078. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62079. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62080. }
  62081. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62082. shadowGenerator.usePercentageCloserFiltering = true;
  62083. }
  62084. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62085. shadowGenerator.useContactHardeningShadow = true;
  62086. }
  62087. if (parsedShadowGenerator.filteringQuality) {
  62088. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62089. }
  62090. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62091. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62092. }
  62093. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62094. shadowGenerator.useExponentialShadowMap = true;
  62095. }
  62096. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62097. shadowGenerator.useBlurExponentialShadowMap = true;
  62098. }
  62099. if (parsedShadowGenerator.depthScale) {
  62100. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62101. }
  62102. if (parsedShadowGenerator.blurScale) {
  62103. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62104. }
  62105. if (parsedShadowGenerator.blurBoxOffset) {
  62106. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62107. }
  62108. if (parsedShadowGenerator.useKernelBlur) {
  62109. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62110. }
  62111. if (parsedShadowGenerator.blurKernel) {
  62112. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62113. }
  62114. if (parsedShadowGenerator.bias !== undefined) {
  62115. shadowGenerator.bias = parsedShadowGenerator.bias;
  62116. }
  62117. if (parsedShadowGenerator.normalBias !== undefined) {
  62118. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62119. }
  62120. if (parsedShadowGenerator.darkness) {
  62121. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62122. }
  62123. if (parsedShadowGenerator.transparencyShadow) {
  62124. shadowGenerator.setTransparencyShadow(true);
  62125. }
  62126. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62127. return shadowGenerator;
  62128. };
  62129. /**
  62130. * Shadow generator mode None: no filtering applied.
  62131. */
  62132. ShadowGenerator.FILTER_NONE = 0;
  62133. /**
  62134. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62135. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62136. */
  62137. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62138. /**
  62139. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62140. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62141. */
  62142. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62143. /**
  62144. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62145. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62146. */
  62147. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62148. /**
  62149. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62150. * edge artifacts on steep falloff.
  62151. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62152. */
  62153. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62154. /**
  62155. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62156. * edge artifacts on steep falloff.
  62157. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62158. */
  62159. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62160. /**
  62161. * Shadow generator mode PCF: Percentage Closer Filtering
  62162. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62163. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62164. */
  62165. ShadowGenerator.FILTER_PCF = 6;
  62166. /**
  62167. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62168. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62169. * Contact Hardening
  62170. */
  62171. ShadowGenerator.FILTER_PCSS = 7;
  62172. /**
  62173. * Reserved for PCF and PCSS
  62174. * Highest Quality.
  62175. *
  62176. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62177. *
  62178. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62179. */
  62180. ShadowGenerator.QUALITY_HIGH = 0;
  62181. /**
  62182. * Reserved for PCF and PCSS
  62183. * Good tradeoff for quality/perf cross devices
  62184. *
  62185. * Execute PCF on a 3*3 kernel.
  62186. *
  62187. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62188. */
  62189. ShadowGenerator.QUALITY_MEDIUM = 1;
  62190. /**
  62191. * Reserved for PCF and PCSS
  62192. * The lowest quality but the fastest.
  62193. *
  62194. * Execute PCF on a 1*1 kernel.
  62195. *
  62196. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62197. */
  62198. ShadowGenerator.QUALITY_LOW = 2;
  62199. return ShadowGenerator;
  62200. }());
  62201. BABYLON.ShadowGenerator = ShadowGenerator;
  62202. })(BABYLON || (BABYLON = {}));
  62203. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62204. "use strict";
  62205. var BABYLON;
  62206. (function (BABYLON) {
  62207. var DefaultLoadingScreen = /** @class */ (function () {
  62208. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62209. if (_loadingText === void 0) { _loadingText = ""; }
  62210. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62211. var _this = this;
  62212. this._renderingCanvas = _renderingCanvas;
  62213. this._loadingText = _loadingText;
  62214. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62215. // Resize
  62216. this._resizeLoadingUI = function () {
  62217. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62218. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62219. if (!_this._loadingDiv) {
  62220. return;
  62221. }
  62222. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62223. _this._loadingDiv.style.left = canvasRect.left + "px";
  62224. _this._loadingDiv.style.top = canvasRect.top + "px";
  62225. _this._loadingDiv.style.width = canvasRect.width + "px";
  62226. _this._loadingDiv.style.height = canvasRect.height + "px";
  62227. };
  62228. }
  62229. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62230. if (this._loadingDiv) {
  62231. // Do not add a loading screen if there is already one
  62232. return;
  62233. }
  62234. this._loadingDiv = document.createElement("div");
  62235. this._loadingDiv.id = "babylonjsLoadingDiv";
  62236. this._loadingDiv.style.opacity = "0";
  62237. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62238. this._loadingDiv.style.pointerEvents = "none";
  62239. // Loading text
  62240. this._loadingTextDiv = document.createElement("div");
  62241. this._loadingTextDiv.style.position = "absolute";
  62242. this._loadingTextDiv.style.left = "0";
  62243. this._loadingTextDiv.style.top = "50%";
  62244. this._loadingTextDiv.style.marginTop = "80px";
  62245. this._loadingTextDiv.style.width = "100%";
  62246. this._loadingTextDiv.style.height = "20px";
  62247. this._loadingTextDiv.style.fontFamily = "Arial";
  62248. this._loadingTextDiv.style.fontSize = "14px";
  62249. this._loadingTextDiv.style.color = "white";
  62250. this._loadingTextDiv.style.textAlign = "center";
  62251. this._loadingTextDiv.innerHTML = "Loading";
  62252. this._loadingDiv.appendChild(this._loadingTextDiv);
  62253. //set the predefined text
  62254. this._loadingTextDiv.innerHTML = this._loadingText;
  62255. // Generating keyframes
  62256. var style = document.createElement('style');
  62257. style.type = 'text/css';
  62258. 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 }";
  62259. style.innerHTML = keyFrames;
  62260. document.getElementsByTagName('head')[0].appendChild(style);
  62261. // Loading img
  62262. var imgBack = new Image();
  62263. 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";
  62264. imgBack.style.position = "absolute";
  62265. imgBack.style.left = "50%";
  62266. imgBack.style.top = "50%";
  62267. imgBack.style.marginLeft = "-60px";
  62268. imgBack.style.marginTop = "-60px";
  62269. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62270. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62271. imgBack.style.transformOrigin = "50% 50%";
  62272. imgBack.style.webkitTransformOrigin = "50% 50%";
  62273. this._loadingDiv.appendChild(imgBack);
  62274. this._resizeLoadingUI();
  62275. window.addEventListener("resize", this._resizeLoadingUI);
  62276. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62277. document.body.appendChild(this._loadingDiv);
  62278. this._loadingDiv.style.opacity = "1";
  62279. };
  62280. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62281. var _this = this;
  62282. if (!this._loadingDiv) {
  62283. return;
  62284. }
  62285. var onTransitionEnd = function () {
  62286. if (!_this._loadingDiv) {
  62287. return;
  62288. }
  62289. document.body.removeChild(_this._loadingDiv);
  62290. window.removeEventListener("resize", _this._resizeLoadingUI);
  62291. _this._loadingDiv = null;
  62292. };
  62293. this._loadingDiv.style.opacity = "0";
  62294. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62295. };
  62296. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62297. set: function (text) {
  62298. this._loadingText = text;
  62299. if (this._loadingTextDiv) {
  62300. this._loadingTextDiv.innerHTML = this._loadingText;
  62301. }
  62302. },
  62303. enumerable: true,
  62304. configurable: true
  62305. });
  62306. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62307. get: function () {
  62308. return this._loadingDivBackgroundColor;
  62309. },
  62310. set: function (color) {
  62311. this._loadingDivBackgroundColor = color;
  62312. if (!this._loadingDiv) {
  62313. return;
  62314. }
  62315. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62316. },
  62317. enumerable: true,
  62318. configurable: true
  62319. });
  62320. return DefaultLoadingScreen;
  62321. }());
  62322. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62323. })(BABYLON || (BABYLON = {}));
  62324. //# sourceMappingURL=babylon.loadingScreen.js.map
  62325. "use strict";
  62326. var BABYLON;
  62327. (function (BABYLON) {
  62328. var SceneLoaderProgressEvent = /** @class */ (function () {
  62329. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62330. this.lengthComputable = lengthComputable;
  62331. this.loaded = loaded;
  62332. this.total = total;
  62333. }
  62334. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62335. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62336. };
  62337. return SceneLoaderProgressEvent;
  62338. }());
  62339. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62340. var SceneLoader = /** @class */ (function () {
  62341. function SceneLoader() {
  62342. }
  62343. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62344. get: function () {
  62345. return 0;
  62346. },
  62347. enumerable: true,
  62348. configurable: true
  62349. });
  62350. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62351. get: function () {
  62352. return 1;
  62353. },
  62354. enumerable: true,
  62355. configurable: true
  62356. });
  62357. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62358. get: function () {
  62359. return 2;
  62360. },
  62361. enumerable: true,
  62362. configurable: true
  62363. });
  62364. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62365. get: function () {
  62366. return 3;
  62367. },
  62368. enumerable: true,
  62369. configurable: true
  62370. });
  62371. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62372. get: function () {
  62373. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62374. },
  62375. set: function (value) {
  62376. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62377. },
  62378. enumerable: true,
  62379. configurable: true
  62380. });
  62381. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62382. get: function () {
  62383. return SceneLoader._ShowLoadingScreen;
  62384. },
  62385. set: function (value) {
  62386. SceneLoader._ShowLoadingScreen = value;
  62387. },
  62388. enumerable: true,
  62389. configurable: true
  62390. });
  62391. Object.defineProperty(SceneLoader, "loggingLevel", {
  62392. get: function () {
  62393. return SceneLoader._loggingLevel;
  62394. },
  62395. set: function (value) {
  62396. SceneLoader._loggingLevel = value;
  62397. },
  62398. enumerable: true,
  62399. configurable: true
  62400. });
  62401. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62402. get: function () {
  62403. return SceneLoader._CleanBoneMatrixWeights;
  62404. },
  62405. set: function (value) {
  62406. SceneLoader._CleanBoneMatrixWeights = value;
  62407. },
  62408. enumerable: true,
  62409. configurable: true
  62410. });
  62411. SceneLoader._getDefaultPlugin = function () {
  62412. return SceneLoader._registeredPlugins[".babylon"];
  62413. };
  62414. SceneLoader._getPluginForExtension = function (extension) {
  62415. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62416. if (registeredPlugin) {
  62417. return registeredPlugin;
  62418. }
  62419. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62420. return SceneLoader._getDefaultPlugin();
  62421. };
  62422. SceneLoader._getPluginForDirectLoad = function (data) {
  62423. for (var extension in SceneLoader._registeredPlugins) {
  62424. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62425. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62426. return SceneLoader._registeredPlugins[extension];
  62427. }
  62428. }
  62429. return SceneLoader._getDefaultPlugin();
  62430. };
  62431. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62432. if (sceneFilename.name) {
  62433. sceneFilename = sceneFilename.name;
  62434. }
  62435. var queryStringPosition = sceneFilename.indexOf("?");
  62436. if (queryStringPosition !== -1) {
  62437. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62438. }
  62439. var dotPosition = sceneFilename.lastIndexOf(".");
  62440. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62441. return SceneLoader._getPluginForExtension(extension);
  62442. };
  62443. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62444. SceneLoader._getDirectLoad = function (sceneFilename) {
  62445. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62446. return sceneFilename.substr(5);
  62447. }
  62448. return null;
  62449. };
  62450. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62451. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62452. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62453. var plugin;
  62454. if (registeredPlugin.plugin.createPlugin) {
  62455. plugin = registeredPlugin.plugin.createPlugin();
  62456. }
  62457. else {
  62458. plugin = registeredPlugin.plugin;
  62459. }
  62460. var useArrayBuffer = registeredPlugin.isBinary;
  62461. var database;
  62462. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62463. var dataCallback = function (data, responseURL) {
  62464. if (scene.isDisposed) {
  62465. onError("Scene has been disposed");
  62466. return;
  62467. }
  62468. scene.database = database;
  62469. onSuccess(plugin, data, responseURL);
  62470. };
  62471. var request = null;
  62472. var pluginDisposed = false;
  62473. var onDisposeObservable = plugin.onDisposeObservable;
  62474. if (onDisposeObservable) {
  62475. onDisposeObservable.add(function () {
  62476. pluginDisposed = true;
  62477. if (request) {
  62478. request.abort();
  62479. request = null;
  62480. }
  62481. onDispose();
  62482. });
  62483. }
  62484. var manifestChecked = function () {
  62485. if (pluginDisposed) {
  62486. return;
  62487. }
  62488. var url = rootUrl + sceneFilename;
  62489. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62490. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62491. } : undefined, database, useArrayBuffer, function (request, exception) {
  62492. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62493. });
  62494. };
  62495. if (directLoad) {
  62496. dataCallback(directLoad);
  62497. return plugin;
  62498. }
  62499. if (rootUrl.indexOf("file:") === -1) {
  62500. if (scene.getEngine().enableOfflineSupport) {
  62501. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62502. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62503. }
  62504. else {
  62505. manifestChecked();
  62506. }
  62507. }
  62508. else {
  62509. var fileOrString = sceneFilename;
  62510. if (fileOrString.name) {
  62511. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62512. }
  62513. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62514. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62515. }
  62516. else {
  62517. onError("Unable to find file named " + sceneFilename);
  62518. }
  62519. }
  62520. return plugin;
  62521. };
  62522. // Public functions
  62523. SceneLoader.GetPluginForExtension = function (extension) {
  62524. return SceneLoader._getPluginForExtension(extension).plugin;
  62525. };
  62526. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62527. return !!SceneLoader._registeredPlugins[extension];
  62528. };
  62529. SceneLoader.RegisterPlugin = function (plugin) {
  62530. if (typeof plugin.extensions === "string") {
  62531. var extension = plugin.extensions;
  62532. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62533. plugin: plugin,
  62534. isBinary: false
  62535. };
  62536. }
  62537. else {
  62538. var extensions = plugin.extensions;
  62539. Object.keys(extensions).forEach(function (extension) {
  62540. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62541. plugin: plugin,
  62542. isBinary: extensions[extension].isBinary
  62543. };
  62544. });
  62545. }
  62546. };
  62547. /**
  62548. * Import meshes into a scene
  62549. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62550. * @param rootUrl a string that defines the root url for scene and resources
  62551. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62552. * @param scene the instance of BABYLON.Scene to append to
  62553. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62554. * @param onProgress a callback with a progress event for each file being loaded
  62555. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62556. * @param pluginExtension the extension used to determine the plugin
  62557. * @returns The loaded plugin
  62558. */
  62559. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62560. if (onSuccess === void 0) { onSuccess = null; }
  62561. if (onProgress === void 0) { onProgress = null; }
  62562. if (onError === void 0) { onError = null; }
  62563. if (pluginExtension === void 0) { pluginExtension = null; }
  62564. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62565. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62566. return null;
  62567. }
  62568. var loadingToken = {};
  62569. scene._addPendingData(loadingToken);
  62570. var disposeHandler = function () {
  62571. scene._removePendingData(loadingToken);
  62572. };
  62573. var errorHandler = function (message, exception) {
  62574. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62575. if (onError) {
  62576. onError(scene, errorMessage, exception);
  62577. }
  62578. else {
  62579. BABYLON.Tools.Error(errorMessage);
  62580. // should the exception be thrown?
  62581. }
  62582. disposeHandler();
  62583. };
  62584. var progressHandler = onProgress ? function (event) {
  62585. try {
  62586. onProgress(event);
  62587. }
  62588. catch (e) {
  62589. errorHandler("Error in onProgress callback", e);
  62590. }
  62591. } : undefined;
  62592. var successHandler = function (meshes, particleSystems, skeletons) {
  62593. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62594. if (onSuccess) {
  62595. try {
  62596. onSuccess(meshes, particleSystems, skeletons);
  62597. }
  62598. catch (e) {
  62599. errorHandler("Error in onSuccess callback", e);
  62600. }
  62601. }
  62602. scene._removePendingData(loadingToken);
  62603. };
  62604. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62605. if (plugin.rewriteRootURL) {
  62606. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62607. }
  62608. if (sceneFilename === "") {
  62609. if (sceneFilename === "") {
  62610. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62611. }
  62612. }
  62613. if (plugin.importMesh) {
  62614. var syncedPlugin = plugin;
  62615. var meshes = new Array();
  62616. var particleSystems = new Array();
  62617. var skeletons = new Array();
  62618. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62619. return;
  62620. }
  62621. scene.loadingPluginName = plugin.name;
  62622. successHandler(meshes, particleSystems, skeletons);
  62623. }
  62624. else {
  62625. var asyncedPlugin = plugin;
  62626. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62627. scene.loadingPluginName = plugin.name;
  62628. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62629. }).catch(function (error) {
  62630. errorHandler(error.message, error);
  62631. });
  62632. }
  62633. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62634. };
  62635. /**
  62636. * Import meshes into a scene
  62637. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62638. * @param rootUrl a string that defines the root url for scene and resources
  62639. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62640. * @param scene the instance of BABYLON.Scene to append to
  62641. * @param onProgress a callback with a progress event for each file being loaded
  62642. * @param pluginExtension the extension used to determine the plugin
  62643. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62644. */
  62645. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62646. if (onProgress === void 0) { onProgress = null; }
  62647. if (pluginExtension === void 0) { pluginExtension = null; }
  62648. return new Promise(function (resolve, reject) {
  62649. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62650. resolve({
  62651. meshes: meshes,
  62652. particleSystems: particleSystems,
  62653. skeletons: skeletons
  62654. });
  62655. }, onProgress, function (scene, message, exception) {
  62656. reject(exception || new Error(message));
  62657. });
  62658. });
  62659. };
  62660. /**
  62661. * Load a scene
  62662. * @param rootUrl a string that defines the root url for scene and resources
  62663. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62664. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62665. * @param onSuccess a callback with the scene when import succeeds
  62666. * @param onProgress a callback with a progress event for each file being loaded
  62667. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62668. * @param pluginExtension the extension used to determine the plugin
  62669. * @returns The loaded plugin
  62670. */
  62671. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62672. if (onSuccess === void 0) { onSuccess = null; }
  62673. if (onProgress === void 0) { onProgress = null; }
  62674. if (onError === void 0) { onError = null; }
  62675. if (pluginExtension === void 0) { pluginExtension = null; }
  62676. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62677. };
  62678. /**
  62679. * Load a scene
  62680. * @param rootUrl a string that defines the root url for scene and resources
  62681. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62682. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62683. * @param onProgress a callback with a progress event for each file being loaded
  62684. * @param pluginExtension the extension used to determine the plugin
  62685. * @returns The loaded scene
  62686. */
  62687. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62688. if (onProgress === void 0) { onProgress = null; }
  62689. if (pluginExtension === void 0) { pluginExtension = null; }
  62690. return new Promise(function (resolve, reject) {
  62691. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62692. resolve(scene);
  62693. }, onProgress, function (scene, message, exception) {
  62694. reject(exception || new Error(message));
  62695. }, pluginExtension);
  62696. });
  62697. };
  62698. /**
  62699. * Append a scene
  62700. * @param rootUrl a string that defines the root url for scene and resources
  62701. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62702. * @param scene is the instance of BABYLON.Scene to append to
  62703. * @param onSuccess a callback with the scene when import succeeds
  62704. * @param onProgress a callback with a progress event for each file being loaded
  62705. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62706. * @param pluginExtension the extension used to determine the plugin
  62707. * @returns The loaded plugin
  62708. */
  62709. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62710. if (onSuccess === void 0) { onSuccess = null; }
  62711. if (onProgress === void 0) { onProgress = null; }
  62712. if (onError === void 0) { onError = null; }
  62713. if (pluginExtension === void 0) { pluginExtension = null; }
  62714. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62715. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62716. return null;
  62717. }
  62718. if (SceneLoader.ShowLoadingScreen) {
  62719. scene.getEngine().displayLoadingUI();
  62720. }
  62721. var loadingToken = {};
  62722. scene._addPendingData(loadingToken);
  62723. var disposeHandler = function () {
  62724. scene._removePendingData(loadingToken);
  62725. scene.getEngine().hideLoadingUI();
  62726. };
  62727. var errorHandler = function (message, exception) {
  62728. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62729. if (onError) {
  62730. onError(scene, errorMessage, exception);
  62731. }
  62732. else {
  62733. BABYLON.Tools.Error(errorMessage);
  62734. // should the exception be thrown?
  62735. }
  62736. disposeHandler();
  62737. };
  62738. var progressHandler = onProgress ? function (event) {
  62739. try {
  62740. onProgress(event);
  62741. }
  62742. catch (e) {
  62743. errorHandler("Error in onProgress callback", e);
  62744. }
  62745. } : undefined;
  62746. var successHandler = function () {
  62747. if (onSuccess) {
  62748. try {
  62749. onSuccess(scene);
  62750. }
  62751. catch (e) {
  62752. errorHandler("Error in onSuccess callback", e);
  62753. }
  62754. }
  62755. scene._removePendingData(loadingToken);
  62756. };
  62757. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62758. if (sceneFilename === "") {
  62759. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62760. }
  62761. if (plugin.load) {
  62762. var syncedPlugin = plugin;
  62763. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  62764. return;
  62765. }
  62766. scene.loadingPluginName = plugin.name;
  62767. successHandler();
  62768. }
  62769. else {
  62770. var asyncedPlugin = plugin;
  62771. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  62772. scene.loadingPluginName = plugin.name;
  62773. successHandler();
  62774. }).catch(function (error) {
  62775. errorHandler(error.message, error);
  62776. });
  62777. }
  62778. if (SceneLoader.ShowLoadingScreen) {
  62779. scene.executeWhenReady(function () {
  62780. scene.getEngine().hideLoadingUI();
  62781. });
  62782. }
  62783. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62784. };
  62785. /**
  62786. * Append a scene
  62787. * @param rootUrl a string that defines the root url for scene and resources
  62788. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62789. * @param scene is the instance of BABYLON.Scene to append to
  62790. * @param onProgress a callback with a progress event for each file being loaded
  62791. * @param pluginExtension the extension used to determine the plugin
  62792. * @returns The given scene
  62793. */
  62794. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62795. if (onProgress === void 0) { onProgress = null; }
  62796. if (pluginExtension === void 0) { pluginExtension = null; }
  62797. return new Promise(function (resolve, reject) {
  62798. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62799. resolve(scene);
  62800. }, onProgress, function (scene, message, exception) {
  62801. reject(exception || new Error(message));
  62802. }, pluginExtension);
  62803. });
  62804. };
  62805. /**
  62806. * Load a scene into an asset container
  62807. * @param rootUrl a string that defines the root url for scene and resources
  62808. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62809. * @param scene is the instance of BABYLON.Scene to append to
  62810. * @param onSuccess a callback with the scene when import succeeds
  62811. * @param onProgress a callback with a progress event for each file being loaded
  62812. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62813. * @param pluginExtension the extension used to determine the plugin
  62814. * @returns The loaded plugin
  62815. */
  62816. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62817. if (onSuccess === void 0) { onSuccess = null; }
  62818. if (onProgress === void 0) { onProgress = null; }
  62819. if (onError === void 0) { onError = null; }
  62820. if (pluginExtension === void 0) { pluginExtension = null; }
  62821. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62822. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62823. return null;
  62824. }
  62825. var loadingToken = {};
  62826. scene._addPendingData(loadingToken);
  62827. var disposeHandler = function () {
  62828. scene._removePendingData(loadingToken);
  62829. };
  62830. var errorHandler = function (message, exception) {
  62831. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62832. if (onError) {
  62833. onError(scene, errorMessage, exception);
  62834. }
  62835. else {
  62836. BABYLON.Tools.Error(errorMessage);
  62837. // should the exception be thrown?
  62838. }
  62839. disposeHandler();
  62840. };
  62841. var progressHandler = onProgress ? function (event) {
  62842. try {
  62843. onProgress(event);
  62844. }
  62845. catch (e) {
  62846. errorHandler("Error in onProgress callback", e);
  62847. }
  62848. } : undefined;
  62849. var successHandler = function (assets) {
  62850. if (onSuccess) {
  62851. try {
  62852. onSuccess(assets);
  62853. }
  62854. catch (e) {
  62855. errorHandler("Error in onSuccess callback", e);
  62856. }
  62857. }
  62858. scene._removePendingData(loadingToken);
  62859. };
  62860. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62861. if (plugin.loadAssetContainer) {
  62862. var syncedPlugin = plugin;
  62863. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62864. if (!assetContainer) {
  62865. return;
  62866. }
  62867. scene.loadingPluginName = plugin.name;
  62868. successHandler(assetContainer);
  62869. }
  62870. else if (plugin.loadAssetContainerAsync) {
  62871. var asyncedPlugin = plugin;
  62872. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62873. scene.loadingPluginName = plugin.name;
  62874. successHandler(assetContainer);
  62875. }).catch(function (error) {
  62876. errorHandler(error.message, error);
  62877. });
  62878. }
  62879. else {
  62880. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62881. }
  62882. if (SceneLoader.ShowLoadingScreen) {
  62883. scene.executeWhenReady(function () {
  62884. scene.getEngine().hideLoadingUI();
  62885. });
  62886. }
  62887. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62888. };
  62889. /**
  62890. * Load a scene into an asset container
  62891. * @param rootUrl a string that defines the root url for scene and resources
  62892. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62893. * @param scene is the instance of BABYLON.Scene to append to
  62894. * @param onProgress a callback with a progress event for each file being loaded
  62895. * @param pluginExtension the extension used to determine the plugin
  62896. * @returns The loaded asset container
  62897. */
  62898. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62899. if (onProgress === void 0) { onProgress = null; }
  62900. if (pluginExtension === void 0) { pluginExtension = null; }
  62901. return new Promise(function (resolve, reject) {
  62902. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62903. resolve(assetContainer);
  62904. }, onProgress, function (scene, message, exception) {
  62905. reject(exception || new Error(message));
  62906. }, pluginExtension);
  62907. });
  62908. };
  62909. // Flags
  62910. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62911. SceneLoader._ShowLoadingScreen = true;
  62912. SceneLoader._CleanBoneMatrixWeights = false;
  62913. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62914. // Members
  62915. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62916. SceneLoader._registeredPlugins = {};
  62917. return SceneLoader;
  62918. }());
  62919. BABYLON.SceneLoader = SceneLoader;
  62920. ;
  62921. })(BABYLON || (BABYLON = {}));
  62922. //# sourceMappingURL=babylon.sceneLoader.js.map
  62923. "use strict";
  62924. var BABYLON;
  62925. (function (BABYLON) {
  62926. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62927. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62928. var parsedMaterial = parsedData.materials[index];
  62929. if (parsedMaterial.id === id) {
  62930. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62931. }
  62932. }
  62933. return null;
  62934. };
  62935. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62936. for (var i in names) {
  62937. if (mesh.name === names[i]) {
  62938. hierarchyIds.push(mesh.id);
  62939. return true;
  62940. }
  62941. }
  62942. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62943. hierarchyIds.push(mesh.id);
  62944. return true;
  62945. }
  62946. return false;
  62947. };
  62948. var logOperation = function (operation, producer) {
  62949. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62950. };
  62951. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62952. if (addToScene === void 0) { addToScene = false; }
  62953. var container = new BABYLON.AssetContainer(scene);
  62954. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62955. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62956. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62957. // and avoid problems with multiple concurrent .babylon loads.
  62958. var log = "importScene has failed JSON parse";
  62959. try {
  62960. var parsedData = JSON.parse(data);
  62961. log = "";
  62962. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62963. var index;
  62964. var cache;
  62965. // Lights
  62966. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62967. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62968. var parsedLight = parsedData.lights[index];
  62969. var light = BABYLON.Light.Parse(parsedLight, scene);
  62970. if (light) {
  62971. container.lights.push(light);
  62972. log += (index === 0 ? "\n\tLights:" : "");
  62973. log += "\n\t\t" + light.toString(fullDetails);
  62974. }
  62975. }
  62976. }
  62977. // Animations
  62978. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62979. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62980. var parsedAnimation = parsedData.animations[index];
  62981. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62982. scene.animations.push(animation);
  62983. container.animations.push(animation);
  62984. log += (index === 0 ? "\n\tAnimations:" : "");
  62985. log += "\n\t\t" + animation.toString(fullDetails);
  62986. }
  62987. }
  62988. // Materials
  62989. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62990. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62991. var parsedMaterial = parsedData.materials[index];
  62992. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62993. container.materials.push(mat);
  62994. log += (index === 0 ? "\n\tMaterials:" : "");
  62995. log += "\n\t\t" + mat.toString(fullDetails);
  62996. }
  62997. }
  62998. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62999. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  63000. var parsedMultiMaterial = parsedData.multiMaterials[index];
  63001. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63002. container.multiMaterials.push(mmat);
  63003. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  63004. log += "\n\t\t" + mmat.toString(fullDetails);
  63005. }
  63006. }
  63007. // Morph targets
  63008. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  63009. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  63010. var managerData = _a[_i];
  63011. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  63012. }
  63013. }
  63014. // Skeletons
  63015. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63016. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  63017. var parsedSkeleton = parsedData.skeletons[index];
  63018. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63019. container.skeletons.push(skeleton);
  63020. log += (index === 0 ? "\n\tSkeletons:" : "");
  63021. log += "\n\t\t" + skeleton.toString(fullDetails);
  63022. }
  63023. }
  63024. // Geometries
  63025. var geometries = parsedData.geometries;
  63026. if (geometries !== undefined && geometries !== null) {
  63027. var addedGeometry = new Array();
  63028. // Boxes
  63029. var boxes = geometries.boxes;
  63030. if (boxes !== undefined && boxes !== null) {
  63031. for (index = 0, cache = boxes.length; index < cache; index++) {
  63032. var parsedBox = boxes[index];
  63033. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  63034. }
  63035. }
  63036. // Spheres
  63037. var spheres = geometries.spheres;
  63038. if (spheres !== undefined && spheres !== null) {
  63039. for (index = 0, cache = spheres.length; index < cache; index++) {
  63040. var parsedSphere = spheres[index];
  63041. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  63042. }
  63043. }
  63044. // Cylinders
  63045. var cylinders = geometries.cylinders;
  63046. if (cylinders !== undefined && cylinders !== null) {
  63047. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63048. var parsedCylinder = cylinders[index];
  63049. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63050. }
  63051. }
  63052. // Toruses
  63053. var toruses = geometries.toruses;
  63054. if (toruses !== undefined && toruses !== null) {
  63055. for (index = 0, cache = toruses.length; index < cache; index++) {
  63056. var parsedTorus = toruses[index];
  63057. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63058. }
  63059. }
  63060. // Grounds
  63061. var grounds = geometries.grounds;
  63062. if (grounds !== undefined && grounds !== null) {
  63063. for (index = 0, cache = grounds.length; index < cache; index++) {
  63064. var parsedGround = grounds[index];
  63065. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63066. }
  63067. }
  63068. // Planes
  63069. var planes = geometries.planes;
  63070. if (planes !== undefined && planes !== null) {
  63071. for (index = 0, cache = planes.length; index < cache; index++) {
  63072. var parsedPlane = planes[index];
  63073. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63074. }
  63075. }
  63076. // TorusKnots
  63077. var torusKnots = geometries.torusKnots;
  63078. if (torusKnots !== undefined && torusKnots !== null) {
  63079. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63080. var parsedTorusKnot = torusKnots[index];
  63081. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63082. }
  63083. }
  63084. // VertexData
  63085. var vertexData = geometries.vertexData;
  63086. if (vertexData !== undefined && vertexData !== null) {
  63087. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63088. var parsedVertexData = vertexData[index];
  63089. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63090. }
  63091. }
  63092. addedGeometry.forEach(function (g) {
  63093. if (g) {
  63094. container.geometries.push(g);
  63095. }
  63096. });
  63097. }
  63098. // Transform nodes
  63099. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63100. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63101. var parsedTransformNode = parsedData.transformNodes[index];
  63102. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63103. container.transformNodes.push(node);
  63104. }
  63105. }
  63106. // Meshes
  63107. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63108. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63109. var parsedMesh = parsedData.meshes[index];
  63110. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63111. container.meshes.push(mesh);
  63112. log += (index === 0 ? "\n\tMeshes:" : "");
  63113. log += "\n\t\t" + mesh.toString(fullDetails);
  63114. }
  63115. }
  63116. // Cameras
  63117. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63118. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63119. var parsedCamera = parsedData.cameras[index];
  63120. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63121. container.cameras.push(camera);
  63122. log += (index === 0 ? "\n\tCameras:" : "");
  63123. log += "\n\t\t" + camera.toString(fullDetails);
  63124. }
  63125. }
  63126. // Browsing all the graph to connect the dots
  63127. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63128. var camera = scene.cameras[index];
  63129. if (camera._waitingParentId) {
  63130. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63131. camera._waitingParentId = null;
  63132. }
  63133. }
  63134. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63135. var light_1 = scene.lights[index];
  63136. if (light_1 && light_1._waitingParentId) {
  63137. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63138. light_1._waitingParentId = null;
  63139. }
  63140. }
  63141. // Sounds
  63142. // TODO: add sound
  63143. var loadedSounds = [];
  63144. var loadedSound;
  63145. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63146. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63147. var parsedSound = parsedData.sounds[index];
  63148. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63149. if (!parsedSound.url)
  63150. parsedSound.url = parsedSound.name;
  63151. if (!loadedSounds[parsedSound.url]) {
  63152. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63153. loadedSounds[parsedSound.url] = loadedSound;
  63154. container.sounds.push(loadedSound);
  63155. }
  63156. else {
  63157. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63158. }
  63159. }
  63160. else {
  63161. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63162. }
  63163. }
  63164. }
  63165. loadedSounds = [];
  63166. // Connect parents & children and parse actions
  63167. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63168. var transformNode = scene.transformNodes[index];
  63169. if (transformNode._waitingParentId) {
  63170. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63171. transformNode._waitingParentId = null;
  63172. }
  63173. }
  63174. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63175. var mesh = scene.meshes[index];
  63176. if (mesh._waitingParentId) {
  63177. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63178. mesh._waitingParentId = null;
  63179. }
  63180. if (mesh._waitingActions) {
  63181. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63182. mesh._waitingActions = null;
  63183. }
  63184. }
  63185. // freeze world matrix application
  63186. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63187. var currentMesh = scene.meshes[index];
  63188. if (currentMesh._waitingFreezeWorldMatrix) {
  63189. currentMesh.freezeWorldMatrix();
  63190. currentMesh._waitingFreezeWorldMatrix = null;
  63191. }
  63192. else {
  63193. currentMesh.computeWorldMatrix(true);
  63194. }
  63195. }
  63196. // Particles Systems
  63197. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63198. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63199. var parsedParticleSystem = parsedData.particleSystems[index];
  63200. if (parsedParticleSystem.activeParticleCount) {
  63201. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63202. container.particleSystems.push(ps);
  63203. }
  63204. else {
  63205. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63206. container.particleSystems.push(ps);
  63207. }
  63208. }
  63209. }
  63210. // Lens flares
  63211. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63212. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63213. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63214. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63215. container.lensFlareSystems.push(lf);
  63216. }
  63217. }
  63218. // Shadows
  63219. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63220. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63221. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63222. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63223. container.shadowGenerators.push(sg);
  63224. }
  63225. }
  63226. // Lights exclusions / inclusions
  63227. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63228. var light_2 = scene.lights[index];
  63229. // Excluded check
  63230. if (light_2._excludedMeshesIds.length > 0) {
  63231. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63232. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63233. if (excludedMesh) {
  63234. light_2.excludedMeshes.push(excludedMesh);
  63235. }
  63236. }
  63237. light_2._excludedMeshesIds = [];
  63238. }
  63239. // Included check
  63240. if (light_2._includedOnlyMeshesIds.length > 0) {
  63241. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63242. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63243. if (includedOnlyMesh) {
  63244. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63245. }
  63246. }
  63247. light_2._includedOnlyMeshesIds = [];
  63248. }
  63249. }
  63250. // Actions (scene)
  63251. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63252. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63253. }
  63254. if (!addToScene) {
  63255. container.removeAllFromScene();
  63256. }
  63257. }
  63258. catch (err) {
  63259. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63260. if (onError) {
  63261. onError(msg, err);
  63262. }
  63263. else {
  63264. BABYLON.Tools.Log(msg);
  63265. throw err;
  63266. }
  63267. }
  63268. finally {
  63269. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63270. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63271. }
  63272. }
  63273. return container;
  63274. };
  63275. BABYLON.SceneLoader.RegisterPlugin({
  63276. name: "babylon.js",
  63277. extensions: ".babylon",
  63278. canDirectLoad: function (data) {
  63279. if (data.indexOf("babylon") !== -1) {
  63280. return true;
  63281. }
  63282. return false;
  63283. },
  63284. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63285. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63286. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63287. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63288. // and avoid problems with multiple concurrent .babylon loads.
  63289. var log = "importMesh has failed JSON parse";
  63290. try {
  63291. var parsedData = JSON.parse(data);
  63292. log = "";
  63293. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63294. if (!meshesNames) {
  63295. meshesNames = null;
  63296. }
  63297. else if (!Array.isArray(meshesNames)) {
  63298. meshesNames = [meshesNames];
  63299. }
  63300. var hierarchyIds = new Array();
  63301. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63302. var loadedSkeletonsIds = [];
  63303. var loadedMaterialsIds = [];
  63304. var index;
  63305. var cache;
  63306. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63307. var parsedMesh = parsedData.meshes[index];
  63308. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63309. if (meshesNames !== null) {
  63310. // Remove found mesh name from list.
  63311. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63312. }
  63313. //Geometry?
  63314. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63315. //does the file contain geometries?
  63316. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63317. //find the correct geometry and add it to the scene
  63318. var found = false;
  63319. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63320. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63321. return;
  63322. }
  63323. else {
  63324. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63325. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63326. switch (geometryType) {
  63327. case "boxes":
  63328. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63329. break;
  63330. case "spheres":
  63331. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63332. break;
  63333. case "cylinders":
  63334. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63335. break;
  63336. case "toruses":
  63337. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63338. break;
  63339. case "grounds":
  63340. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63341. break;
  63342. case "planes":
  63343. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63344. break;
  63345. case "torusKnots":
  63346. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63347. break;
  63348. case "vertexData":
  63349. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63350. break;
  63351. }
  63352. found = true;
  63353. }
  63354. });
  63355. }
  63356. });
  63357. if (found === false) {
  63358. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63359. }
  63360. }
  63361. }
  63362. // Material ?
  63363. if (parsedMesh.materialId) {
  63364. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63365. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63366. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63367. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63368. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63369. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63370. var subMatId = parsedMultiMaterial.materials[matIndex];
  63371. loadedMaterialsIds.push(subMatId);
  63372. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63373. if (mat) {
  63374. log += "\n\tMaterial " + mat.toString(fullDetails);
  63375. }
  63376. }
  63377. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63378. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63379. if (mmat) {
  63380. materialFound = true;
  63381. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63382. }
  63383. break;
  63384. }
  63385. }
  63386. }
  63387. if (materialFound === false) {
  63388. loadedMaterialsIds.push(parsedMesh.materialId);
  63389. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63390. if (!mat) {
  63391. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63392. }
  63393. else {
  63394. log += "\n\tMaterial " + mat.toString(fullDetails);
  63395. }
  63396. }
  63397. }
  63398. // Skeleton ?
  63399. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63400. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63401. if (skeletonAlreadyLoaded === false) {
  63402. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63403. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63404. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63405. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63406. skeletons.push(skeleton);
  63407. loadedSkeletonsIds.push(parsedSkeleton.id);
  63408. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63409. }
  63410. }
  63411. }
  63412. }
  63413. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63414. meshes.push(mesh);
  63415. log += "\n\tMesh " + mesh.toString(fullDetails);
  63416. }
  63417. }
  63418. // Connecting parents
  63419. var currentMesh;
  63420. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63421. currentMesh = scene.meshes[index];
  63422. if (currentMesh._waitingParentId) {
  63423. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63424. currentMesh._waitingParentId = null;
  63425. }
  63426. }
  63427. // freeze and compute world matrix application
  63428. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63429. currentMesh = scene.meshes[index];
  63430. if (currentMesh._waitingFreezeWorldMatrix) {
  63431. currentMesh.freezeWorldMatrix();
  63432. currentMesh._waitingFreezeWorldMatrix = null;
  63433. }
  63434. else {
  63435. currentMesh.computeWorldMatrix(true);
  63436. }
  63437. }
  63438. }
  63439. // Particles
  63440. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63441. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63442. var parsedParticleSystem = parsedData.particleSystems[index];
  63443. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63444. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63445. }
  63446. }
  63447. }
  63448. return true;
  63449. }
  63450. catch (err) {
  63451. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63452. if (onError) {
  63453. onError(msg, err);
  63454. }
  63455. else {
  63456. BABYLON.Tools.Log(msg);
  63457. throw err;
  63458. }
  63459. }
  63460. finally {
  63461. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63462. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63463. }
  63464. }
  63465. return false;
  63466. },
  63467. load: function (scene, data, rootUrl, onError) {
  63468. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63469. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63470. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63471. // and avoid problems with multiple concurrent .babylon loads.
  63472. var log = "importScene has failed JSON parse";
  63473. try {
  63474. var parsedData = JSON.parse(data);
  63475. log = "";
  63476. // Scene
  63477. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63478. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63479. }
  63480. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63481. scene.autoClear = parsedData.autoClear;
  63482. }
  63483. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63484. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63485. }
  63486. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63487. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63488. }
  63489. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63490. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63491. }
  63492. // Fog
  63493. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63494. scene.fogMode = parsedData.fogMode;
  63495. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63496. scene.fogStart = parsedData.fogStart;
  63497. scene.fogEnd = parsedData.fogEnd;
  63498. scene.fogDensity = parsedData.fogDensity;
  63499. log += "\tFog mode for scene: ";
  63500. switch (scene.fogMode) {
  63501. // getters not compiling, so using hardcoded
  63502. case 1:
  63503. log += "exp\n";
  63504. break;
  63505. case 2:
  63506. log += "exp2\n";
  63507. break;
  63508. case 3:
  63509. log += "linear\n";
  63510. break;
  63511. }
  63512. }
  63513. //Physics
  63514. if (parsedData.physicsEnabled) {
  63515. var physicsPlugin;
  63516. if (parsedData.physicsEngine === "cannon") {
  63517. physicsPlugin = new BABYLON.CannonJSPlugin();
  63518. }
  63519. else if (parsedData.physicsEngine === "oimo") {
  63520. physicsPlugin = new BABYLON.OimoJSPlugin();
  63521. }
  63522. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63523. //else - default engine, which is currently oimo
  63524. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63525. scene.enablePhysics(physicsGravity, physicsPlugin);
  63526. }
  63527. // Metadata
  63528. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63529. scene.metadata = parsedData.metadata;
  63530. }
  63531. //collisions, if defined. otherwise, default is true
  63532. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63533. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63534. }
  63535. scene.workerCollisions = !!parsedData.workerCollisions;
  63536. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63537. if (!container) {
  63538. return false;
  63539. }
  63540. if (parsedData.autoAnimate) {
  63541. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63542. }
  63543. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63544. scene.setActiveCameraByID(parsedData.activeCameraID);
  63545. }
  63546. // Environment texture
  63547. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63548. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63549. if (parsedData.createDefaultSkybox === true) {
  63550. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63551. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63552. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63553. }
  63554. }
  63555. // Finish
  63556. return true;
  63557. }
  63558. catch (err) {
  63559. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63560. if (onError) {
  63561. onError(msg, err);
  63562. }
  63563. else {
  63564. BABYLON.Tools.Log(msg);
  63565. throw err;
  63566. }
  63567. }
  63568. finally {
  63569. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63570. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63571. }
  63572. }
  63573. return false;
  63574. },
  63575. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63576. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63577. return container;
  63578. }
  63579. });
  63580. })(BABYLON || (BABYLON = {}));
  63581. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63582. "use strict";
  63583. var BABYLON;
  63584. (function (BABYLON) {
  63585. var FilesInput = /** @class */ (function () {
  63586. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63587. this.onProcessFileCallback = function () { return true; };
  63588. this._engine = engine;
  63589. this._currentScene = scene;
  63590. this._sceneLoadedCallback = sceneLoadedCallback;
  63591. this._progressCallback = progressCallback;
  63592. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63593. this._textureLoadingCallback = textureLoadingCallback;
  63594. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63595. this._onReloadCallback = onReloadCallback;
  63596. this._errorCallback = errorCallback;
  63597. }
  63598. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63599. var _this = this;
  63600. if (elementToMonitor) {
  63601. this._elementToMonitor = elementToMonitor;
  63602. this._dragEnterHandler = function (e) { _this.drag(e); };
  63603. this._dragOverHandler = function (e) { _this.drag(e); };
  63604. this._dropHandler = function (e) { _this.drop(e); };
  63605. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63606. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63607. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63608. }
  63609. };
  63610. FilesInput.prototype.dispose = function () {
  63611. if (!this._elementToMonitor) {
  63612. return;
  63613. }
  63614. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63615. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63616. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63617. };
  63618. FilesInput.prototype.renderFunction = function () {
  63619. if (this._additionalRenderLoopLogicCallback) {
  63620. this._additionalRenderLoopLogicCallback();
  63621. }
  63622. if (this._currentScene) {
  63623. if (this._textureLoadingCallback) {
  63624. var remaining = this._currentScene.getWaitingItemsCount();
  63625. if (remaining > 0) {
  63626. this._textureLoadingCallback(remaining);
  63627. }
  63628. }
  63629. this._currentScene.render();
  63630. }
  63631. };
  63632. FilesInput.prototype.drag = function (e) {
  63633. e.stopPropagation();
  63634. e.preventDefault();
  63635. };
  63636. FilesInput.prototype.drop = function (eventDrop) {
  63637. eventDrop.stopPropagation();
  63638. eventDrop.preventDefault();
  63639. this.loadFiles(eventDrop);
  63640. };
  63641. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63642. var _this = this;
  63643. var reader = folder.createReader();
  63644. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63645. reader.readEntries(function (entries) {
  63646. remaining.count += entries.length;
  63647. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63648. var entry = entries_1[_i];
  63649. if (entry.isFile) {
  63650. entry.file(function (file) {
  63651. file.correctName = relativePath + file.name;
  63652. files.push(file);
  63653. if (--remaining.count === 0) {
  63654. callback();
  63655. }
  63656. });
  63657. }
  63658. else if (entry.isDirectory) {
  63659. _this._traverseFolder(entry, files, remaining, callback);
  63660. }
  63661. }
  63662. if (--remaining.count) {
  63663. callback();
  63664. }
  63665. });
  63666. };
  63667. FilesInput.prototype._processFiles = function (files) {
  63668. for (var i = 0; i < files.length; i++) {
  63669. var name = files[i].correctName.toLowerCase();
  63670. var extension = name.split('.').pop();
  63671. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63672. continue;
  63673. }
  63674. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63675. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63676. this._sceneFileToLoad = files[i];
  63677. }
  63678. else {
  63679. FilesInput.FilesToLoad[name] = files[i];
  63680. }
  63681. }
  63682. };
  63683. FilesInput.prototype.loadFiles = function (event) {
  63684. var _this = this;
  63685. if (this._startingProcessingFilesCallback)
  63686. this._startingProcessingFilesCallback();
  63687. // Handling data transfer via drag'n'drop
  63688. if (event && event.dataTransfer && event.dataTransfer.files) {
  63689. this._filesToLoad = event.dataTransfer.files;
  63690. }
  63691. // Handling files from input files
  63692. if (event && event.target && event.target.files) {
  63693. this._filesToLoad = event.target.files;
  63694. }
  63695. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63696. var files_1 = new Array();
  63697. var folders = [];
  63698. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63699. for (var i = 0; i < this._filesToLoad.length; i++) {
  63700. var fileToLoad = this._filesToLoad[i];
  63701. var name_1 = fileToLoad.name.toLowerCase();
  63702. var entry = void 0;
  63703. fileToLoad.correctName = name_1;
  63704. if (items) {
  63705. var item = items[i];
  63706. if (item.getAsEntry) {
  63707. entry = item.getAsEntry();
  63708. }
  63709. else if (item.webkitGetAsEntry) {
  63710. entry = item.webkitGetAsEntry();
  63711. }
  63712. }
  63713. if (!entry) {
  63714. files_1.push(fileToLoad);
  63715. }
  63716. else {
  63717. if (entry.isDirectory) {
  63718. folders.push(entry);
  63719. }
  63720. else {
  63721. files_1.push(fileToLoad);
  63722. }
  63723. }
  63724. }
  63725. if (folders.length === 0) {
  63726. this._processFiles(files_1);
  63727. this._processReload();
  63728. }
  63729. else {
  63730. var remaining = { count: folders.length };
  63731. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  63732. var folder = folders_1[_i];
  63733. this._traverseFolder(folder, files_1, remaining, function () {
  63734. _this._processFiles(files_1);
  63735. if (remaining.count === 0) {
  63736. _this._processReload();
  63737. }
  63738. });
  63739. }
  63740. }
  63741. }
  63742. };
  63743. FilesInput.prototype._processReload = function () {
  63744. if (this._onReloadCallback) {
  63745. this._onReloadCallback(this._sceneFileToLoad);
  63746. }
  63747. else {
  63748. this.reload();
  63749. }
  63750. };
  63751. FilesInput.prototype.reload = function () {
  63752. var _this = this;
  63753. // If a scene file has been provided
  63754. if (this._sceneFileToLoad) {
  63755. if (this._currentScene) {
  63756. if (BABYLON.Tools.errorsCount > 0) {
  63757. BABYLON.Tools.ClearLogCache();
  63758. }
  63759. this._engine.stopRenderLoop();
  63760. this._currentScene.dispose();
  63761. }
  63762. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  63763. if (_this._progressCallback) {
  63764. _this._progressCallback(progress);
  63765. }
  63766. }).then(function (scene) {
  63767. _this._currentScene = scene;
  63768. if (_this._sceneLoadedCallback) {
  63769. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  63770. }
  63771. // Wait for textures and shaders to be ready
  63772. _this._currentScene.executeWhenReady(function () {
  63773. _this._engine.runRenderLoop(function () {
  63774. _this.renderFunction();
  63775. });
  63776. });
  63777. }).catch(function (error) {
  63778. if (_this._errorCallback) {
  63779. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  63780. }
  63781. });
  63782. }
  63783. else {
  63784. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63785. }
  63786. };
  63787. FilesInput.FilesToLoad = {};
  63788. return FilesInput;
  63789. }());
  63790. BABYLON.FilesInput = FilesInput;
  63791. })(BABYLON || (BABYLON = {}));
  63792. //# sourceMappingURL=babylon.filesInput.js.map
  63793. "use strict";
  63794. var BABYLON;
  63795. (function (BABYLON) {
  63796. /**
  63797. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63798. * The underlying implementation relies on an associative array to ensure the best performances.
  63799. * The value can be anything including 'null' but except 'undefined'
  63800. */
  63801. var StringDictionary = /** @class */ (function () {
  63802. function StringDictionary() {
  63803. this._count = 0;
  63804. this._data = {};
  63805. }
  63806. /**
  63807. * This will clear this dictionary and copy the content from the 'source' one.
  63808. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63809. * @param source the dictionary to take the content from and copy to this dictionary
  63810. */
  63811. StringDictionary.prototype.copyFrom = function (source) {
  63812. var _this = this;
  63813. this.clear();
  63814. source.forEach(function (t, v) { return _this.add(t, v); });
  63815. };
  63816. /**
  63817. * Get a value based from its key
  63818. * @param key the given key to get the matching value from
  63819. * @return the value if found, otherwise undefined is returned
  63820. */
  63821. StringDictionary.prototype.get = function (key) {
  63822. var val = this._data[key];
  63823. if (val !== undefined) {
  63824. return val;
  63825. }
  63826. return undefined;
  63827. };
  63828. /**
  63829. * Get a value from its key or add it if it doesn't exist.
  63830. * This method will ensure you that a given key/data will be present in the dictionary.
  63831. * @param key the given key to get the matching value from
  63832. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63833. * The factory will only be invoked if there's no data for the given key.
  63834. * @return the value corresponding to the key.
  63835. */
  63836. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63837. var val = this.get(key);
  63838. if (val !== undefined) {
  63839. return val;
  63840. }
  63841. val = factory(key);
  63842. if (val) {
  63843. this.add(key, val);
  63844. }
  63845. return val;
  63846. };
  63847. /**
  63848. * Get a value from its key if present in the dictionary otherwise add it
  63849. * @param key the key to get the value from
  63850. * @param val if there's no such key/value pair in the dictionary add it with this value
  63851. * @return the value corresponding to the key
  63852. */
  63853. StringDictionary.prototype.getOrAdd = function (key, val) {
  63854. var curVal = this.get(key);
  63855. if (curVal !== undefined) {
  63856. return curVal;
  63857. }
  63858. this.add(key, val);
  63859. return val;
  63860. };
  63861. /**
  63862. * Check if there's a given key in the dictionary
  63863. * @param key the key to check for
  63864. * @return true if the key is present, false otherwise
  63865. */
  63866. StringDictionary.prototype.contains = function (key) {
  63867. return this._data[key] !== undefined;
  63868. };
  63869. /**
  63870. * Add a new key and its corresponding value
  63871. * @param key the key to add
  63872. * @param value the value corresponding to the key
  63873. * @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
  63874. */
  63875. StringDictionary.prototype.add = function (key, value) {
  63876. if (this._data[key] !== undefined) {
  63877. return false;
  63878. }
  63879. this._data[key] = value;
  63880. ++this._count;
  63881. return true;
  63882. };
  63883. StringDictionary.prototype.set = function (key, value) {
  63884. if (this._data[key] === undefined) {
  63885. return false;
  63886. }
  63887. this._data[key] = value;
  63888. return true;
  63889. };
  63890. /**
  63891. * Get the element of the given key and remove it from the dictionary
  63892. * @param key
  63893. */
  63894. StringDictionary.prototype.getAndRemove = function (key) {
  63895. var val = this.get(key);
  63896. if (val !== undefined) {
  63897. delete this._data[key];
  63898. --this._count;
  63899. return val;
  63900. }
  63901. return null;
  63902. };
  63903. /**
  63904. * Remove a key/value from the dictionary.
  63905. * @param key the key to remove
  63906. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63907. */
  63908. StringDictionary.prototype.remove = function (key) {
  63909. if (this.contains(key)) {
  63910. delete this._data[key];
  63911. --this._count;
  63912. return true;
  63913. }
  63914. return false;
  63915. };
  63916. /**
  63917. * Clear the whole content of the dictionary
  63918. */
  63919. StringDictionary.prototype.clear = function () {
  63920. this._data = {};
  63921. this._count = 0;
  63922. };
  63923. Object.defineProperty(StringDictionary.prototype, "count", {
  63924. get: function () {
  63925. return this._count;
  63926. },
  63927. enumerable: true,
  63928. configurable: true
  63929. });
  63930. /**
  63931. * Execute a callback on each key/val of the dictionary.
  63932. * Note that you can remove any element in this dictionary in the callback implementation
  63933. * @param callback the callback to execute on a given key/value pair
  63934. */
  63935. StringDictionary.prototype.forEach = function (callback) {
  63936. for (var cur in this._data) {
  63937. var val = this._data[cur];
  63938. callback(cur, val);
  63939. }
  63940. };
  63941. /**
  63942. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63943. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63944. * Note that you can remove any element in this dictionary in the callback implementation
  63945. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63946. */
  63947. StringDictionary.prototype.first = function (callback) {
  63948. for (var cur in this._data) {
  63949. var val = this._data[cur];
  63950. var res = callback(cur, val);
  63951. if (res) {
  63952. return res;
  63953. }
  63954. }
  63955. return null;
  63956. };
  63957. return StringDictionary;
  63958. }());
  63959. BABYLON.StringDictionary = StringDictionary;
  63960. })(BABYLON || (BABYLON = {}));
  63961. //# sourceMappingURL=babylon.stringDictionary.js.map
  63962. "use strict";
  63963. var BABYLON;
  63964. (function (BABYLON) {
  63965. var Tags = /** @class */ (function () {
  63966. function Tags() {
  63967. }
  63968. Tags.EnableFor = function (obj) {
  63969. obj._tags = obj._tags || {};
  63970. obj.hasTags = function () {
  63971. return Tags.HasTags(obj);
  63972. };
  63973. obj.addTags = function (tagsString) {
  63974. return Tags.AddTagsTo(obj, tagsString);
  63975. };
  63976. obj.removeTags = function (tagsString) {
  63977. return Tags.RemoveTagsFrom(obj, tagsString);
  63978. };
  63979. obj.matchesTagsQuery = function (tagsQuery) {
  63980. return Tags.MatchesQuery(obj, tagsQuery);
  63981. };
  63982. };
  63983. Tags.DisableFor = function (obj) {
  63984. delete obj._tags;
  63985. delete obj.hasTags;
  63986. delete obj.addTags;
  63987. delete obj.removeTags;
  63988. delete obj.matchesTagsQuery;
  63989. };
  63990. Tags.HasTags = function (obj) {
  63991. if (!obj._tags) {
  63992. return false;
  63993. }
  63994. return !BABYLON.Tools.IsEmpty(obj._tags);
  63995. };
  63996. Tags.GetTags = function (obj, asString) {
  63997. if (asString === void 0) { asString = true; }
  63998. if (!obj._tags) {
  63999. return null;
  64000. }
  64001. if (asString) {
  64002. var tagsArray = [];
  64003. for (var tag in obj._tags) {
  64004. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  64005. tagsArray.push(tag);
  64006. }
  64007. }
  64008. return tagsArray.join(" ");
  64009. }
  64010. else {
  64011. return obj._tags;
  64012. }
  64013. };
  64014. // the tags 'true' and 'false' are reserved and cannot be used as tags
  64015. // a tag cannot start with '||', '&&', and '!'
  64016. // it cannot contain whitespaces
  64017. Tags.AddTagsTo = function (obj, tagsString) {
  64018. if (!tagsString) {
  64019. return;
  64020. }
  64021. if (typeof tagsString !== "string") {
  64022. return;
  64023. }
  64024. var tags = tagsString.split(" ");
  64025. tags.forEach(function (tag, index, array) {
  64026. Tags._AddTagTo(obj, tag);
  64027. });
  64028. };
  64029. Tags._AddTagTo = function (obj, tag) {
  64030. tag = tag.trim();
  64031. if (tag === "" || tag === "true" || tag === "false") {
  64032. return;
  64033. }
  64034. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  64035. return;
  64036. }
  64037. Tags.EnableFor(obj);
  64038. obj._tags[tag] = true;
  64039. };
  64040. Tags.RemoveTagsFrom = function (obj, tagsString) {
  64041. if (!Tags.HasTags(obj)) {
  64042. return;
  64043. }
  64044. var tags = tagsString.split(" ");
  64045. for (var t in tags) {
  64046. Tags._RemoveTagFrom(obj, tags[t]);
  64047. }
  64048. };
  64049. Tags._RemoveTagFrom = function (obj, tag) {
  64050. delete obj._tags[tag];
  64051. };
  64052. Tags.MatchesQuery = function (obj, tagsQuery) {
  64053. if (tagsQuery === undefined) {
  64054. return true;
  64055. }
  64056. if (tagsQuery === "") {
  64057. return Tags.HasTags(obj);
  64058. }
  64059. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64060. };
  64061. return Tags;
  64062. }());
  64063. BABYLON.Tags = Tags;
  64064. })(BABYLON || (BABYLON = {}));
  64065. //# sourceMappingURL=babylon.tags.js.map
  64066. "use strict";
  64067. var BABYLON;
  64068. (function (BABYLON) {
  64069. var AndOrNotEvaluator = /** @class */ (function () {
  64070. function AndOrNotEvaluator() {
  64071. }
  64072. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64073. if (!query.match(/\([^\(\)]*\)/g)) {
  64074. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64075. }
  64076. else {
  64077. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64078. // remove parenthesis
  64079. r = r.slice(1, r.length - 1);
  64080. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64081. });
  64082. }
  64083. if (query === "true") {
  64084. return true;
  64085. }
  64086. if (query === "false") {
  64087. return false;
  64088. }
  64089. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64090. };
  64091. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64092. evaluateCallback = evaluateCallback || (function (r) {
  64093. return r === "true" ? true : false;
  64094. });
  64095. var result;
  64096. var or = parenthesisContent.split("||");
  64097. for (var i in or) {
  64098. if (or.hasOwnProperty(i)) {
  64099. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64100. var and = ori.split("&&");
  64101. if (and.length > 1) {
  64102. for (var j = 0; j < and.length; ++j) {
  64103. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64104. if (andj !== "true" && andj !== "false") {
  64105. if (andj[0] === "!") {
  64106. result = !evaluateCallback(andj.substring(1));
  64107. }
  64108. else {
  64109. result = evaluateCallback(andj);
  64110. }
  64111. }
  64112. else {
  64113. result = andj === "true" ? true : false;
  64114. }
  64115. if (!result) {
  64116. ori = "false";
  64117. break;
  64118. }
  64119. }
  64120. }
  64121. if (result || ori === "true") {
  64122. result = true;
  64123. break;
  64124. }
  64125. // result equals false (or undefined)
  64126. if (ori !== "true" && ori !== "false") {
  64127. if (ori[0] === "!") {
  64128. result = !evaluateCallback(ori.substring(1));
  64129. }
  64130. else {
  64131. result = evaluateCallback(ori);
  64132. }
  64133. }
  64134. else {
  64135. result = ori === "true" ? true : false;
  64136. }
  64137. }
  64138. }
  64139. // the whole parenthesis scope is replaced by 'true' or 'false'
  64140. return result ? "true" : "false";
  64141. };
  64142. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64143. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64144. // remove whitespaces
  64145. r = r.replace(/[\s]/g, function () { return ""; });
  64146. return r.length % 2 ? "!" : "";
  64147. });
  64148. booleanString = booleanString.trim();
  64149. if (booleanString === "!true") {
  64150. booleanString = "false";
  64151. }
  64152. else if (booleanString === "!false") {
  64153. booleanString = "true";
  64154. }
  64155. return booleanString;
  64156. };
  64157. return AndOrNotEvaluator;
  64158. }());
  64159. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64160. })(BABYLON || (BABYLON = {}));
  64161. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64162. "use strict";
  64163. var BABYLON;
  64164. (function (BABYLON) {
  64165. var Database = /** @class */ (function () {
  64166. function Database(urlToScene, callbackManifestChecked) {
  64167. // Handling various flavors of prefixed version of IndexedDB
  64168. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64169. this.callbackManifestChecked = callbackManifestChecked;
  64170. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64171. this.db = null;
  64172. this._enableSceneOffline = false;
  64173. this._enableTexturesOffline = false;
  64174. this.manifestVersionFound = 0;
  64175. this.mustUpdateRessources = false;
  64176. this.hasReachedQuota = false;
  64177. if (!Database.IDBStorageEnabled) {
  64178. this.callbackManifestChecked(true);
  64179. }
  64180. else {
  64181. this.checkManifestFile();
  64182. }
  64183. }
  64184. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64185. get: function () {
  64186. return this._enableSceneOffline;
  64187. },
  64188. enumerable: true,
  64189. configurable: true
  64190. });
  64191. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64192. get: function () {
  64193. return this._enableTexturesOffline;
  64194. },
  64195. enumerable: true,
  64196. configurable: true
  64197. });
  64198. Database.prototype.checkManifestFile = function () {
  64199. var _this = this;
  64200. var noManifestFile = function () {
  64201. _this._enableSceneOffline = false;
  64202. _this._enableTexturesOffline = false;
  64203. _this.callbackManifestChecked(false);
  64204. };
  64205. var timeStampUsed = false;
  64206. var manifestURL = this.currentSceneUrl + ".manifest";
  64207. var xhr = new XMLHttpRequest();
  64208. if (navigator.onLine) {
  64209. // Adding a timestamp to by-pass browsers' cache
  64210. timeStampUsed = true;
  64211. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64212. }
  64213. xhr.open("GET", manifestURL, true);
  64214. xhr.addEventListener("load", function () {
  64215. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64216. try {
  64217. var manifestFile = JSON.parse(xhr.response);
  64218. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64219. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64220. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64221. _this.manifestVersionFound = manifestFile.version;
  64222. }
  64223. if (_this.callbackManifestChecked) {
  64224. _this.callbackManifestChecked(true);
  64225. }
  64226. }
  64227. catch (ex) {
  64228. noManifestFile();
  64229. }
  64230. }
  64231. else {
  64232. noManifestFile();
  64233. }
  64234. }, false);
  64235. xhr.addEventListener("error", function (event) {
  64236. if (timeStampUsed) {
  64237. timeStampUsed = false;
  64238. // Let's retry without the timeStamp
  64239. // It could fail when coupled with HTML5 Offline API
  64240. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64241. xhr.open("GET", retryManifestURL, true);
  64242. xhr.send();
  64243. }
  64244. else {
  64245. noManifestFile();
  64246. }
  64247. }, false);
  64248. try {
  64249. xhr.send();
  64250. }
  64251. catch (ex) {
  64252. BABYLON.Tools.Error("Error on XHR send request.");
  64253. this.callbackManifestChecked(false);
  64254. }
  64255. };
  64256. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64257. var _this = this;
  64258. var handleError = function () {
  64259. _this.isSupported = false;
  64260. if (errorCallback)
  64261. errorCallback();
  64262. };
  64263. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64264. // Your browser doesn't support IndexedDB
  64265. this.isSupported = false;
  64266. if (errorCallback)
  64267. errorCallback();
  64268. }
  64269. else {
  64270. // If the DB hasn't been opened or created yet
  64271. if (!this.db) {
  64272. this.hasReachedQuota = false;
  64273. this.isSupported = true;
  64274. var request = this.idbFactory.open("babylonjs", 1);
  64275. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64276. request.onerror = function (event) {
  64277. handleError();
  64278. };
  64279. // executes when a version change transaction cannot complete due to other active transactions
  64280. request.onblocked = function (event) {
  64281. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64282. handleError();
  64283. };
  64284. // DB has been opened successfully
  64285. request.onsuccess = function (event) {
  64286. _this.db = request.result;
  64287. successCallback();
  64288. };
  64289. // Initialization of the DB. Creating Scenes & Textures stores
  64290. request.onupgradeneeded = function (event) {
  64291. _this.db = (event.target).result;
  64292. if (_this.db) {
  64293. try {
  64294. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64295. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64296. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64297. }
  64298. catch (ex) {
  64299. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64300. handleError();
  64301. }
  64302. }
  64303. };
  64304. }
  64305. else {
  64306. if (successCallback)
  64307. successCallback();
  64308. }
  64309. }
  64310. };
  64311. Database.prototype.loadImageFromDB = function (url, image) {
  64312. var _this = this;
  64313. var completeURL = Database.ReturnFullUrlLocation(url);
  64314. var saveAndLoadImage = function () {
  64315. if (!_this.hasReachedQuota && _this.db !== null) {
  64316. // the texture is not yet in the DB, let's try to save it
  64317. _this._saveImageIntoDBAsync(completeURL, image);
  64318. }
  64319. else {
  64320. image.src = url;
  64321. }
  64322. };
  64323. if (!this.mustUpdateRessources) {
  64324. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64325. }
  64326. else {
  64327. saveAndLoadImage();
  64328. }
  64329. };
  64330. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64331. if (this.isSupported && this.db !== null) {
  64332. var texture;
  64333. var transaction = this.db.transaction(["textures"]);
  64334. transaction.onabort = function (event) {
  64335. image.src = url;
  64336. };
  64337. transaction.oncomplete = function (event) {
  64338. var blobTextureURL;
  64339. if (texture) {
  64340. var URL = window.URL || window.webkitURL;
  64341. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64342. image.onerror = function () {
  64343. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64344. image.src = url;
  64345. };
  64346. image.src = blobTextureURL;
  64347. }
  64348. else {
  64349. notInDBCallback();
  64350. }
  64351. };
  64352. var getRequest = transaction.objectStore("textures").get(url);
  64353. getRequest.onsuccess = function (event) {
  64354. texture = (event.target).result;
  64355. };
  64356. getRequest.onerror = function (event) {
  64357. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64358. image.src = url;
  64359. };
  64360. }
  64361. else {
  64362. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64363. image.src = url;
  64364. }
  64365. };
  64366. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64367. var _this = this;
  64368. if (this.isSupported) {
  64369. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64370. var generateBlobUrl = function () {
  64371. var blobTextureURL;
  64372. if (blob) {
  64373. var URL = window.URL || window.webkitURL;
  64374. try {
  64375. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64376. }
  64377. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64378. catch (ex) {
  64379. blobTextureURL = URL.createObjectURL(blob);
  64380. }
  64381. }
  64382. if (blobTextureURL) {
  64383. image.src = blobTextureURL;
  64384. }
  64385. };
  64386. if (Database.IsUASupportingBlobStorage) {
  64387. var xhr = new XMLHttpRequest(), blob;
  64388. xhr.open("GET", url, true);
  64389. xhr.responseType = "blob";
  64390. xhr.addEventListener("load", function () {
  64391. if (xhr.status === 200 && _this.db) {
  64392. // Blob as response (XHR2)
  64393. blob = xhr.response;
  64394. var transaction = _this.db.transaction(["textures"], "readwrite");
  64395. // the transaction could abort because of a QuotaExceededError error
  64396. transaction.onabort = function (event) {
  64397. try {
  64398. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64399. var srcElement = (event.srcElement || event.target);
  64400. var error = srcElement.error;
  64401. if (error && error.name === "QuotaExceededError") {
  64402. _this.hasReachedQuota = true;
  64403. }
  64404. }
  64405. catch (ex) { }
  64406. generateBlobUrl();
  64407. };
  64408. transaction.oncomplete = function (event) {
  64409. generateBlobUrl();
  64410. };
  64411. var newTexture = { textureUrl: url, data: blob };
  64412. try {
  64413. // Put the blob into the dabase
  64414. var addRequest = transaction.objectStore("textures").put(newTexture);
  64415. addRequest.onsuccess = function (event) {
  64416. };
  64417. addRequest.onerror = function (event) {
  64418. generateBlobUrl();
  64419. };
  64420. }
  64421. catch (ex) {
  64422. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64423. if (ex.code === 25) {
  64424. Database.IsUASupportingBlobStorage = false;
  64425. }
  64426. image.src = url;
  64427. }
  64428. }
  64429. else {
  64430. image.src = url;
  64431. }
  64432. }, false);
  64433. xhr.addEventListener("error", function (event) {
  64434. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64435. image.src = url;
  64436. }, false);
  64437. xhr.send();
  64438. }
  64439. else {
  64440. image.src = url;
  64441. }
  64442. }
  64443. else {
  64444. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64445. image.src = url;
  64446. }
  64447. };
  64448. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64449. var _this = this;
  64450. var updateVersion = function () {
  64451. // the version is not yet in the DB or we need to update it
  64452. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64453. };
  64454. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64455. };
  64456. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64457. var _this = this;
  64458. if (this.isSupported && this.db) {
  64459. var version;
  64460. try {
  64461. var transaction = this.db.transaction(["versions"]);
  64462. transaction.oncomplete = function (event) {
  64463. if (version) {
  64464. // If the version in the JSON file is > than the version in DB
  64465. if (_this.manifestVersionFound > version.data) {
  64466. _this.mustUpdateRessources = true;
  64467. updateInDBCallback();
  64468. }
  64469. else {
  64470. callback(version.data);
  64471. }
  64472. }
  64473. else {
  64474. _this.mustUpdateRessources = true;
  64475. updateInDBCallback();
  64476. }
  64477. };
  64478. transaction.onabort = function (event) {
  64479. callback(-1);
  64480. };
  64481. var getRequest = transaction.objectStore("versions").get(url);
  64482. getRequest.onsuccess = function (event) {
  64483. version = (event.target).result;
  64484. };
  64485. getRequest.onerror = function (event) {
  64486. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64487. callback(-1);
  64488. };
  64489. }
  64490. catch (ex) {
  64491. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64492. callback(-1);
  64493. }
  64494. }
  64495. else {
  64496. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64497. callback(-1);
  64498. }
  64499. };
  64500. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64501. var _this = this;
  64502. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64503. try {
  64504. // Open a transaction to the database
  64505. var transaction = this.db.transaction(["versions"], "readwrite");
  64506. // the transaction could abort because of a QuotaExceededError error
  64507. transaction.onabort = function (event) {
  64508. try {
  64509. var error = event.srcElement['error'];
  64510. if (error && error.name === "QuotaExceededError") {
  64511. _this.hasReachedQuota = true;
  64512. }
  64513. }
  64514. catch (ex) { }
  64515. callback(-1);
  64516. };
  64517. transaction.oncomplete = function (event) {
  64518. callback(_this.manifestVersionFound);
  64519. };
  64520. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64521. // Put the scene into the database
  64522. var addRequest = transaction.objectStore("versions").put(newVersion);
  64523. addRequest.onsuccess = function (event) {
  64524. };
  64525. addRequest.onerror = function (event) {
  64526. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64527. };
  64528. }
  64529. catch (ex) {
  64530. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64531. callback(-1);
  64532. }
  64533. }
  64534. else {
  64535. callback(-1);
  64536. }
  64537. };
  64538. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64539. var _this = this;
  64540. var completeUrl = Database.ReturnFullUrlLocation(url);
  64541. var saveAndLoadFile = function () {
  64542. // the scene is not yet in the DB, let's try to save it
  64543. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64544. };
  64545. this._checkVersionFromDB(completeUrl, function (version) {
  64546. if (version !== -1) {
  64547. if (!_this.mustUpdateRessources) {
  64548. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64549. }
  64550. else {
  64551. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64552. }
  64553. }
  64554. else {
  64555. if (errorCallback) {
  64556. errorCallback();
  64557. }
  64558. }
  64559. });
  64560. };
  64561. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64562. if (this.isSupported && this.db) {
  64563. var targetStore;
  64564. if (url.indexOf(".babylon") !== -1) {
  64565. targetStore = "scenes";
  64566. }
  64567. else {
  64568. targetStore = "textures";
  64569. }
  64570. var file;
  64571. var transaction = this.db.transaction([targetStore]);
  64572. transaction.oncomplete = function (event) {
  64573. if (file) {
  64574. callback(file.data);
  64575. }
  64576. else {
  64577. notInDBCallback();
  64578. }
  64579. };
  64580. transaction.onabort = function (event) {
  64581. notInDBCallback();
  64582. };
  64583. var getRequest = transaction.objectStore(targetStore).get(url);
  64584. getRequest.onsuccess = function (event) {
  64585. file = (event.target).result;
  64586. };
  64587. getRequest.onerror = function (event) {
  64588. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64589. notInDBCallback();
  64590. };
  64591. }
  64592. else {
  64593. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64594. callback();
  64595. }
  64596. };
  64597. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64598. var _this = this;
  64599. if (this.isSupported) {
  64600. var targetStore;
  64601. if (url.indexOf(".babylon") !== -1) {
  64602. targetStore = "scenes";
  64603. }
  64604. else {
  64605. targetStore = "textures";
  64606. }
  64607. // Create XHR
  64608. var xhr = new XMLHttpRequest();
  64609. var fileData;
  64610. xhr.open("GET", url, true);
  64611. if (useArrayBuffer) {
  64612. xhr.responseType = "arraybuffer";
  64613. }
  64614. if (progressCallback) {
  64615. xhr.onprogress = progressCallback;
  64616. }
  64617. xhr.addEventListener("load", function () {
  64618. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64619. // Blob as response (XHR2)
  64620. //fileData = xhr.responseText;
  64621. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64622. if (!_this.hasReachedQuota && _this.db) {
  64623. // Open a transaction to the database
  64624. var transaction = _this.db.transaction([targetStore], "readwrite");
  64625. // the transaction could abort because of a QuotaExceededError error
  64626. transaction.onabort = function (event) {
  64627. try {
  64628. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64629. var error = event.srcElement['error'];
  64630. if (error && error.name === "QuotaExceededError") {
  64631. _this.hasReachedQuota = true;
  64632. }
  64633. }
  64634. catch (ex) { }
  64635. callback(fileData);
  64636. };
  64637. transaction.oncomplete = function (event) {
  64638. callback(fileData);
  64639. };
  64640. var newFile;
  64641. if (targetStore === "scenes") {
  64642. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64643. }
  64644. else {
  64645. newFile = { textureUrl: url, data: fileData };
  64646. }
  64647. try {
  64648. // Put the scene into the database
  64649. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64650. addRequest.onsuccess = function (event) {
  64651. };
  64652. addRequest.onerror = function (event) {
  64653. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64654. };
  64655. }
  64656. catch (ex) {
  64657. callback(fileData);
  64658. }
  64659. }
  64660. else {
  64661. callback(fileData);
  64662. }
  64663. }
  64664. else {
  64665. callback();
  64666. }
  64667. }, false);
  64668. xhr.addEventListener("error", function (event) {
  64669. BABYLON.Tools.Error("error on XHR request.");
  64670. callback();
  64671. }, false);
  64672. xhr.send();
  64673. }
  64674. else {
  64675. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64676. callback();
  64677. }
  64678. };
  64679. Database.IsUASupportingBlobStorage = true;
  64680. Database.IDBStorageEnabled = true;
  64681. Database.parseURL = function (url) {
  64682. var a = document.createElement('a');
  64683. a.href = url;
  64684. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64685. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64686. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64687. return absLocation;
  64688. };
  64689. Database.ReturnFullUrlLocation = function (url) {
  64690. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64691. return (Database.parseURL(window.location.href) + url);
  64692. }
  64693. else {
  64694. return url;
  64695. }
  64696. };
  64697. return Database;
  64698. }());
  64699. BABYLON.Database = Database;
  64700. })(BABYLON || (BABYLON = {}));
  64701. //# sourceMappingURL=babylon.database.js.map
  64702. "use strict";
  64703. var BABYLON;
  64704. (function (BABYLON) {
  64705. var FresnelParameters = /** @class */ (function () {
  64706. function FresnelParameters() {
  64707. this._isEnabled = true;
  64708. this.leftColor = BABYLON.Color3.White();
  64709. this.rightColor = BABYLON.Color3.Black();
  64710. this.bias = 0;
  64711. this.power = 1;
  64712. }
  64713. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64714. get: function () {
  64715. return this._isEnabled;
  64716. },
  64717. set: function (value) {
  64718. if (this._isEnabled === value) {
  64719. return;
  64720. }
  64721. this._isEnabled = value;
  64722. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64723. },
  64724. enumerable: true,
  64725. configurable: true
  64726. });
  64727. FresnelParameters.prototype.clone = function () {
  64728. var newFresnelParameters = new FresnelParameters();
  64729. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  64730. return newFresnelParameters;
  64731. };
  64732. FresnelParameters.prototype.serialize = function () {
  64733. var serializationObject = {};
  64734. serializationObject.isEnabled = this.isEnabled;
  64735. serializationObject.leftColor = this.leftColor;
  64736. serializationObject.rightColor = this.rightColor;
  64737. serializationObject.bias = this.bias;
  64738. serializationObject.power = this.power;
  64739. return serializationObject;
  64740. };
  64741. FresnelParameters.Parse = function (parsedFresnelParameters) {
  64742. var fresnelParameters = new FresnelParameters();
  64743. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  64744. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  64745. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  64746. fresnelParameters.bias = parsedFresnelParameters.bias;
  64747. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  64748. return fresnelParameters;
  64749. };
  64750. return FresnelParameters;
  64751. }());
  64752. BABYLON.FresnelParameters = FresnelParameters;
  64753. })(BABYLON || (BABYLON = {}));
  64754. //# sourceMappingURL=babylon.fresnelParameters.js.map
  64755. "use strict";
  64756. var BABYLON;
  64757. (function (BABYLON) {
  64758. var MultiMaterial = /** @class */ (function (_super) {
  64759. __extends(MultiMaterial, _super);
  64760. function MultiMaterial(name, scene) {
  64761. var _this = _super.call(this, name, scene, true) || this;
  64762. scene.multiMaterials.push(_this);
  64763. _this.subMaterials = new Array();
  64764. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  64765. return _this;
  64766. }
  64767. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  64768. get: function () {
  64769. return this._subMaterials;
  64770. },
  64771. set: function (value) {
  64772. this._subMaterials = value;
  64773. this._hookArray(value);
  64774. },
  64775. enumerable: true,
  64776. configurable: true
  64777. });
  64778. MultiMaterial.prototype._hookArray = function (array) {
  64779. var _this = this;
  64780. var oldPush = array.push;
  64781. array.push = function () {
  64782. var items = [];
  64783. for (var _i = 0; _i < arguments.length; _i++) {
  64784. items[_i] = arguments[_i];
  64785. }
  64786. var result = oldPush.apply(array, items);
  64787. _this._markAllSubMeshesAsTexturesDirty();
  64788. return result;
  64789. };
  64790. var oldSplice = array.splice;
  64791. array.splice = function (index, deleteCount) {
  64792. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64793. _this._markAllSubMeshesAsTexturesDirty();
  64794. return deleted;
  64795. };
  64796. };
  64797. // Properties
  64798. MultiMaterial.prototype.getSubMaterial = function (index) {
  64799. if (index < 0 || index >= this.subMaterials.length) {
  64800. return this.getScene().defaultMaterial;
  64801. }
  64802. return this.subMaterials[index];
  64803. };
  64804. MultiMaterial.prototype.getActiveTextures = function () {
  64805. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64806. if (subMaterial) {
  64807. return subMaterial.getActiveTextures();
  64808. }
  64809. else {
  64810. return [];
  64811. }
  64812. }));
  64813. var _a;
  64814. };
  64815. // Methods
  64816. MultiMaterial.prototype.getClassName = function () {
  64817. return "MultiMaterial";
  64818. };
  64819. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64820. for (var index = 0; index < this.subMaterials.length; index++) {
  64821. var subMaterial = this.subMaterials[index];
  64822. if (subMaterial) {
  64823. if (subMaterial.storeEffectOnSubMeshes) {
  64824. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64825. return false;
  64826. }
  64827. continue;
  64828. }
  64829. if (!subMaterial.isReady(mesh)) {
  64830. return false;
  64831. }
  64832. }
  64833. }
  64834. return true;
  64835. };
  64836. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  64837. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  64838. for (var index = 0; index < this.subMaterials.length; index++) {
  64839. var subMaterial = null;
  64840. var current = this.subMaterials[index];
  64841. if (cloneChildren && current) {
  64842. subMaterial = current.clone(name + "-" + current.name);
  64843. }
  64844. else {
  64845. subMaterial = this.subMaterials[index];
  64846. }
  64847. newMultiMaterial.subMaterials.push(subMaterial);
  64848. }
  64849. return newMultiMaterial;
  64850. };
  64851. MultiMaterial.prototype.serialize = function () {
  64852. var serializationObject = {};
  64853. serializationObject.name = this.name;
  64854. serializationObject.id = this.id;
  64855. if (BABYLON.Tags) {
  64856. serializationObject.tags = BABYLON.Tags.GetTags(this);
  64857. }
  64858. serializationObject.materials = [];
  64859. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  64860. var subMat = this.subMaterials[matIndex];
  64861. if (subMat) {
  64862. serializationObject.materials.push(subMat.id);
  64863. }
  64864. else {
  64865. serializationObject.materials.push(null);
  64866. }
  64867. }
  64868. return serializationObject;
  64869. };
  64870. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64871. var scene = this.getScene();
  64872. if (!scene) {
  64873. return;
  64874. }
  64875. var index = scene.multiMaterials.indexOf(this);
  64876. if (index >= 0) {
  64877. scene.multiMaterials.splice(index, 1);
  64878. }
  64879. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64880. };
  64881. return MultiMaterial;
  64882. }(BABYLON.Material));
  64883. BABYLON.MultiMaterial = MultiMaterial;
  64884. })(BABYLON || (BABYLON = {}));
  64885. //# sourceMappingURL=babylon.multiMaterial.js.map
  64886. "use strict";
  64887. var BABYLON;
  64888. (function (BABYLON) {
  64889. var FreeCameraTouchInput = /** @class */ (function () {
  64890. function FreeCameraTouchInput() {
  64891. this._offsetX = null;
  64892. this._offsetY = null;
  64893. this._pointerPressed = new Array();
  64894. this.touchAngularSensibility = 200000.0;
  64895. this.touchMoveSensibility = 250.0;
  64896. }
  64897. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64898. var _this = this;
  64899. var previousPosition = null;
  64900. if (this._pointerInput === undefined) {
  64901. this._onLostFocus = function (evt) {
  64902. _this._offsetX = null;
  64903. _this._offsetY = null;
  64904. };
  64905. this._pointerInput = function (p, s) {
  64906. var evt = p.event;
  64907. if (evt.pointerType === "mouse") {
  64908. return;
  64909. }
  64910. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64911. if (!noPreventDefault) {
  64912. evt.preventDefault();
  64913. }
  64914. _this._pointerPressed.push(evt.pointerId);
  64915. if (_this._pointerPressed.length !== 1) {
  64916. return;
  64917. }
  64918. previousPosition = {
  64919. x: evt.clientX,
  64920. y: evt.clientY
  64921. };
  64922. }
  64923. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64924. if (!noPreventDefault) {
  64925. evt.preventDefault();
  64926. }
  64927. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64928. if (index === -1) {
  64929. return;
  64930. }
  64931. _this._pointerPressed.splice(index, 1);
  64932. if (index != 0) {
  64933. return;
  64934. }
  64935. previousPosition = null;
  64936. _this._offsetX = null;
  64937. _this._offsetY = null;
  64938. }
  64939. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64940. if (!noPreventDefault) {
  64941. evt.preventDefault();
  64942. }
  64943. if (!previousPosition) {
  64944. return;
  64945. }
  64946. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64947. if (index != 0) {
  64948. return;
  64949. }
  64950. _this._offsetX = evt.clientX - previousPosition.x;
  64951. _this._offsetY = -(evt.clientY - previousPosition.y);
  64952. }
  64953. };
  64954. }
  64955. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64956. if (this._onLostFocus) {
  64957. element.addEventListener("blur", this._onLostFocus);
  64958. }
  64959. };
  64960. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64961. if (this._pointerInput && element) {
  64962. if (this._observer) {
  64963. this.camera.getScene().onPointerObservable.remove(this._observer);
  64964. this._observer = null;
  64965. }
  64966. if (this._onLostFocus) {
  64967. element.removeEventListener("blur", this._onLostFocus);
  64968. this._onLostFocus = null;
  64969. }
  64970. this._pointerPressed = [];
  64971. this._offsetX = null;
  64972. this._offsetY = null;
  64973. }
  64974. };
  64975. FreeCameraTouchInput.prototype.checkInputs = function () {
  64976. if (this._offsetX && this._offsetY) {
  64977. var camera = this.camera;
  64978. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64979. if (this._pointerPressed.length > 1) {
  64980. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64981. }
  64982. else {
  64983. var speed = camera._computeLocalCameraSpeed();
  64984. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64985. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64986. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64987. }
  64988. }
  64989. };
  64990. FreeCameraTouchInput.prototype.getClassName = function () {
  64991. return "FreeCameraTouchInput";
  64992. };
  64993. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64994. return "touch";
  64995. };
  64996. __decorate([
  64997. BABYLON.serialize()
  64998. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64999. __decorate([
  65000. BABYLON.serialize()
  65001. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  65002. return FreeCameraTouchInput;
  65003. }());
  65004. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  65005. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  65006. })(BABYLON || (BABYLON = {}));
  65007. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  65008. "use strict";
  65009. var BABYLON;
  65010. (function (BABYLON) {
  65011. // We're mainly based on the logic defined into the FreeCamera code
  65012. var TouchCamera = /** @class */ (function (_super) {
  65013. __extends(TouchCamera, _super);
  65014. //-- end properties for backward compatibility for inputs
  65015. function TouchCamera(name, position, scene) {
  65016. var _this = _super.call(this, name, position, scene) || this;
  65017. _this.inputs.addTouch();
  65018. _this._setupInputs();
  65019. return _this;
  65020. }
  65021. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  65022. //-- Begin properties for backward compatibility for inputs
  65023. get: function () {
  65024. var touch = this.inputs.attached["touch"];
  65025. if (touch)
  65026. return touch.touchAngularSensibility;
  65027. return 0;
  65028. },
  65029. set: function (value) {
  65030. var touch = this.inputs.attached["touch"];
  65031. if (touch)
  65032. touch.touchAngularSensibility = value;
  65033. },
  65034. enumerable: true,
  65035. configurable: true
  65036. });
  65037. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  65038. get: function () {
  65039. var touch = this.inputs.attached["touch"];
  65040. if (touch)
  65041. return touch.touchMoveSensibility;
  65042. return 0;
  65043. },
  65044. set: function (value) {
  65045. var touch = this.inputs.attached["touch"];
  65046. if (touch)
  65047. touch.touchMoveSensibility = value;
  65048. },
  65049. enumerable: true,
  65050. configurable: true
  65051. });
  65052. TouchCamera.prototype.getClassName = function () {
  65053. return "TouchCamera";
  65054. };
  65055. TouchCamera.prototype._setupInputs = function () {
  65056. var mouse = this.inputs.attached["mouse"];
  65057. if (mouse) {
  65058. mouse.touchEnabled = false;
  65059. }
  65060. };
  65061. return TouchCamera;
  65062. }(BABYLON.FreeCamera));
  65063. BABYLON.TouchCamera = TouchCamera;
  65064. })(BABYLON || (BABYLON = {}));
  65065. //# sourceMappingURL=babylon.touchCamera.js.map
  65066. "use strict";
  65067. var BABYLON;
  65068. (function (BABYLON) {
  65069. var ProceduralTexture = /** @class */ (function (_super) {
  65070. __extends(ProceduralTexture, _super);
  65071. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65072. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65073. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65074. if (isCube === void 0) { isCube = false; }
  65075. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65076. _this.isCube = isCube;
  65077. _this.isEnabled = true;
  65078. _this._currentRefreshId = -1;
  65079. _this._refreshRate = 1;
  65080. _this._vertexBuffers = {};
  65081. _this._uniforms = new Array();
  65082. _this._samplers = new Array();
  65083. _this._textures = {};
  65084. _this._floats = {};
  65085. _this._floatsArrays = {};
  65086. _this._colors3 = {};
  65087. _this._colors4 = {};
  65088. _this._vectors2 = {};
  65089. _this._vectors3 = {};
  65090. _this._matrices = {};
  65091. _this._fallbackTextureUsed = false;
  65092. scene._proceduralTextures.push(_this);
  65093. _this._engine = scene.getEngine();
  65094. _this.name = name;
  65095. _this.isRenderTarget = true;
  65096. _this._size = size;
  65097. _this._generateMipMaps = generateMipMaps;
  65098. _this.setFragment(fragment);
  65099. _this._fallbackTexture = fallbackTexture;
  65100. if (isCube) {
  65101. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65102. _this.setFloat("face", 0);
  65103. }
  65104. else {
  65105. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65106. }
  65107. // VBO
  65108. var vertices = [];
  65109. vertices.push(1, 1);
  65110. vertices.push(-1, 1);
  65111. vertices.push(-1, -1);
  65112. vertices.push(1, -1);
  65113. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65114. _this._createIndexBuffer();
  65115. return _this;
  65116. }
  65117. ProceduralTexture.prototype._createIndexBuffer = function () {
  65118. var engine = this._engine;
  65119. // Indices
  65120. var indices = [];
  65121. indices.push(0);
  65122. indices.push(1);
  65123. indices.push(2);
  65124. indices.push(0);
  65125. indices.push(2);
  65126. indices.push(3);
  65127. this._indexBuffer = engine.createIndexBuffer(indices);
  65128. };
  65129. ProceduralTexture.prototype._rebuild = function () {
  65130. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65131. if (vb) {
  65132. vb._rebuild();
  65133. }
  65134. this._createIndexBuffer();
  65135. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65136. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65137. }
  65138. };
  65139. ProceduralTexture.prototype.reset = function () {
  65140. if (this._effect === undefined) {
  65141. return;
  65142. }
  65143. var engine = this._engine;
  65144. engine._releaseEffect(this._effect);
  65145. };
  65146. ProceduralTexture.prototype.isReady = function () {
  65147. var _this = this;
  65148. var engine = this._engine;
  65149. var shaders;
  65150. if (!this._fragment) {
  65151. return false;
  65152. }
  65153. if (this._fallbackTextureUsed) {
  65154. return true;
  65155. }
  65156. if (this._fragment.fragmentElement !== undefined) {
  65157. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65158. }
  65159. else {
  65160. shaders = { vertex: "procedural", fragment: this._fragment };
  65161. }
  65162. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65163. _this.releaseInternalTexture();
  65164. if (_this._fallbackTexture) {
  65165. _this._texture = _this._fallbackTexture._texture;
  65166. if (_this._texture) {
  65167. _this._texture.incrementReferences();
  65168. }
  65169. }
  65170. _this._fallbackTextureUsed = true;
  65171. });
  65172. return this._effect.isReady();
  65173. };
  65174. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65175. this._currentRefreshId = -1;
  65176. };
  65177. ProceduralTexture.prototype.setFragment = function (fragment) {
  65178. this._fragment = fragment;
  65179. };
  65180. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65181. get: function () {
  65182. return this._refreshRate;
  65183. },
  65184. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65185. set: function (value) {
  65186. this._refreshRate = value;
  65187. this.resetRefreshCounter();
  65188. },
  65189. enumerable: true,
  65190. configurable: true
  65191. });
  65192. ProceduralTexture.prototype._shouldRender = function () {
  65193. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65194. return false;
  65195. }
  65196. if (this._fallbackTextureUsed) {
  65197. return false;
  65198. }
  65199. if (this._currentRefreshId === -1) {
  65200. this._currentRefreshId = 1;
  65201. return true;
  65202. }
  65203. if (this.refreshRate === this._currentRefreshId) {
  65204. this._currentRefreshId = 1;
  65205. return true;
  65206. }
  65207. this._currentRefreshId++;
  65208. return false;
  65209. };
  65210. ProceduralTexture.prototype.getRenderSize = function () {
  65211. return this._size;
  65212. };
  65213. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65214. if (this._fallbackTextureUsed) {
  65215. return;
  65216. }
  65217. this.releaseInternalTexture();
  65218. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65219. };
  65220. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65221. if (this._uniforms.indexOf(uniformName) === -1) {
  65222. this._uniforms.push(uniformName);
  65223. }
  65224. };
  65225. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65226. if (this._samplers.indexOf(name) === -1) {
  65227. this._samplers.push(name);
  65228. }
  65229. this._textures[name] = texture;
  65230. return this;
  65231. };
  65232. ProceduralTexture.prototype.setFloat = function (name, value) {
  65233. this._checkUniform(name);
  65234. this._floats[name] = value;
  65235. return this;
  65236. };
  65237. ProceduralTexture.prototype.setFloats = function (name, value) {
  65238. this._checkUniform(name);
  65239. this._floatsArrays[name] = value;
  65240. return this;
  65241. };
  65242. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65243. this._checkUniform(name);
  65244. this._colors3[name] = value;
  65245. return this;
  65246. };
  65247. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65248. this._checkUniform(name);
  65249. this._colors4[name] = value;
  65250. return this;
  65251. };
  65252. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65253. this._checkUniform(name);
  65254. this._vectors2[name] = value;
  65255. return this;
  65256. };
  65257. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65258. this._checkUniform(name);
  65259. this._vectors3[name] = value;
  65260. return this;
  65261. };
  65262. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65263. this._checkUniform(name);
  65264. this._matrices[name] = value;
  65265. return this;
  65266. };
  65267. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65268. var scene = this.getScene();
  65269. if (!scene) {
  65270. return;
  65271. }
  65272. var engine = this._engine;
  65273. // Render
  65274. engine.enableEffect(this._effect);
  65275. engine.setState(false);
  65276. // Texture
  65277. for (var name in this._textures) {
  65278. this._effect.setTexture(name, this._textures[name]);
  65279. }
  65280. // Float
  65281. for (name in this._floats) {
  65282. this._effect.setFloat(name, this._floats[name]);
  65283. }
  65284. // Floats
  65285. for (name in this._floatsArrays) {
  65286. this._effect.setArray(name, this._floatsArrays[name]);
  65287. }
  65288. // Color3
  65289. for (name in this._colors3) {
  65290. this._effect.setColor3(name, this._colors3[name]);
  65291. }
  65292. // Color4
  65293. for (name in this._colors4) {
  65294. var color = this._colors4[name];
  65295. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65296. }
  65297. // Vector2
  65298. for (name in this._vectors2) {
  65299. this._effect.setVector2(name, this._vectors2[name]);
  65300. }
  65301. // Vector3
  65302. for (name in this._vectors3) {
  65303. this._effect.setVector3(name, this._vectors3[name]);
  65304. }
  65305. // Matrix
  65306. for (name in this._matrices) {
  65307. this._effect.setMatrix(name, this._matrices[name]);
  65308. }
  65309. if (!this._texture) {
  65310. return;
  65311. }
  65312. if (this.isCube) {
  65313. for (var face = 0; face < 6; face++) {
  65314. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65315. // VBOs
  65316. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65317. this._effect.setFloat("face", face);
  65318. // Clear
  65319. engine.clear(scene.clearColor, true, true, true);
  65320. // Draw order
  65321. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65322. // Mipmaps
  65323. if (face === 5) {
  65324. engine.generateMipMapsForCubemap(this._texture);
  65325. }
  65326. }
  65327. }
  65328. else {
  65329. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65330. // VBOs
  65331. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65332. // Clear
  65333. engine.clear(scene.clearColor, true, true, true);
  65334. // Draw order
  65335. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65336. }
  65337. // Unbind
  65338. engine.unBindFramebuffer(this._texture, this.isCube);
  65339. if (this.onGenerated) {
  65340. this.onGenerated();
  65341. }
  65342. };
  65343. ProceduralTexture.prototype.clone = function () {
  65344. var textureSize = this.getSize();
  65345. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65346. // Base texture
  65347. newTexture.hasAlpha = this.hasAlpha;
  65348. newTexture.level = this.level;
  65349. // RenderTarget Texture
  65350. newTexture.coordinatesMode = this.coordinatesMode;
  65351. return newTexture;
  65352. };
  65353. ProceduralTexture.prototype.dispose = function () {
  65354. var scene = this.getScene();
  65355. if (!scene) {
  65356. return;
  65357. }
  65358. var index = scene._proceduralTextures.indexOf(this);
  65359. if (index >= 0) {
  65360. scene._proceduralTextures.splice(index, 1);
  65361. }
  65362. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65363. if (vertexBuffer) {
  65364. vertexBuffer.dispose();
  65365. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65366. }
  65367. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65368. this._indexBuffer = null;
  65369. }
  65370. _super.prototype.dispose.call(this);
  65371. };
  65372. return ProceduralTexture;
  65373. }(BABYLON.Texture));
  65374. BABYLON.ProceduralTexture = ProceduralTexture;
  65375. })(BABYLON || (BABYLON = {}));
  65376. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65377. "use strict";
  65378. var BABYLON;
  65379. (function (BABYLON) {
  65380. var CustomProceduralTexture = /** @class */ (function (_super) {
  65381. __extends(CustomProceduralTexture, _super);
  65382. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65383. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65384. _this._animate = true;
  65385. _this._time = 0;
  65386. _this._texturePath = texturePath;
  65387. //Try to load json
  65388. _this.loadJson(texturePath);
  65389. _this.refreshRate = 1;
  65390. return _this;
  65391. }
  65392. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65393. var _this = this;
  65394. var noConfigFile = function () {
  65395. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65396. try {
  65397. _this.setFragment(_this._texturePath);
  65398. }
  65399. catch (ex) {
  65400. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65401. }
  65402. };
  65403. var configFileUrl = jsonUrl + "/config.json";
  65404. var xhr = new XMLHttpRequest();
  65405. xhr.open("GET", configFileUrl, true);
  65406. xhr.addEventListener("load", function () {
  65407. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65408. try {
  65409. _this._config = JSON.parse(xhr.response);
  65410. _this.updateShaderUniforms();
  65411. _this.updateTextures();
  65412. _this.setFragment(_this._texturePath + "/custom");
  65413. _this._animate = _this._config.animate;
  65414. _this.refreshRate = _this._config.refreshrate;
  65415. }
  65416. catch (ex) {
  65417. noConfigFile();
  65418. }
  65419. }
  65420. else {
  65421. noConfigFile();
  65422. }
  65423. }, false);
  65424. xhr.addEventListener("error", function () {
  65425. noConfigFile();
  65426. }, false);
  65427. try {
  65428. xhr.send();
  65429. }
  65430. catch (ex) {
  65431. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65432. }
  65433. };
  65434. CustomProceduralTexture.prototype.isReady = function () {
  65435. if (!_super.prototype.isReady.call(this)) {
  65436. return false;
  65437. }
  65438. for (var name in this._textures) {
  65439. var texture = this._textures[name];
  65440. if (!texture.isReady()) {
  65441. return false;
  65442. }
  65443. }
  65444. return true;
  65445. };
  65446. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65447. var scene = this.getScene();
  65448. if (this._animate && scene) {
  65449. this._time += scene.getAnimationRatio() * 0.03;
  65450. this.updateShaderUniforms();
  65451. }
  65452. _super.prototype.render.call(this, useCameraPostProcess);
  65453. };
  65454. CustomProceduralTexture.prototype.updateTextures = function () {
  65455. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65456. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65457. }
  65458. };
  65459. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65460. if (this._config) {
  65461. for (var j = 0; j < this._config.uniforms.length; j++) {
  65462. var uniform = this._config.uniforms[j];
  65463. switch (uniform.type) {
  65464. case "float":
  65465. this.setFloat(uniform.name, uniform.value);
  65466. break;
  65467. case "color3":
  65468. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65469. break;
  65470. case "color4":
  65471. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65472. break;
  65473. case "vector2":
  65474. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65475. break;
  65476. case "vector3":
  65477. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65478. break;
  65479. }
  65480. }
  65481. }
  65482. this.setFloat("time", this._time);
  65483. };
  65484. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65485. get: function () {
  65486. return this._animate;
  65487. },
  65488. set: function (value) {
  65489. this._animate = value;
  65490. },
  65491. enumerable: true,
  65492. configurable: true
  65493. });
  65494. return CustomProceduralTexture;
  65495. }(BABYLON.ProceduralTexture));
  65496. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65497. })(BABYLON || (BABYLON = {}));
  65498. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65499. "use strict";
  65500. var BABYLON;
  65501. (function (BABYLON) {
  65502. var FreeCameraGamepadInput = /** @class */ (function () {
  65503. function FreeCameraGamepadInput() {
  65504. this.gamepadAngularSensibility = 200;
  65505. this.gamepadMoveSensibility = 40;
  65506. // private members
  65507. this._cameraTransform = BABYLON.Matrix.Identity();
  65508. this._deltaTransform = BABYLON.Vector3.Zero();
  65509. this._vector3 = BABYLON.Vector3.Zero();
  65510. this._vector2 = BABYLON.Vector2.Zero();
  65511. }
  65512. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65513. var _this = this;
  65514. var manager = this.camera.getScene().gamepadManager;
  65515. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65516. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65517. // prioritize XBOX gamepads.
  65518. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65519. _this.gamepad = gamepad;
  65520. }
  65521. }
  65522. });
  65523. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65524. if (_this.gamepad === gamepad) {
  65525. _this.gamepad = null;
  65526. }
  65527. });
  65528. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65529. };
  65530. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65531. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65532. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65533. this.gamepad = null;
  65534. };
  65535. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65536. if (this.gamepad && this.gamepad.leftStick) {
  65537. var camera = this.camera;
  65538. var LSValues = this.gamepad.leftStick;
  65539. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65540. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65541. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65542. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65543. var RSValues = this.gamepad.rightStick;
  65544. if (RSValues) {
  65545. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65546. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65547. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65548. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65549. }
  65550. else {
  65551. RSValues = { x: 0, y: 0 };
  65552. }
  65553. if (!camera.rotationQuaternion) {
  65554. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65555. }
  65556. else {
  65557. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65558. }
  65559. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65560. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65561. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65562. camera.cameraDirection.addInPlace(this._deltaTransform);
  65563. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65564. camera.cameraRotation.addInPlace(this._vector2);
  65565. }
  65566. };
  65567. FreeCameraGamepadInput.prototype.getClassName = function () {
  65568. return "FreeCameraGamepadInput";
  65569. };
  65570. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65571. return "gamepad";
  65572. };
  65573. __decorate([
  65574. BABYLON.serialize()
  65575. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65576. __decorate([
  65577. BABYLON.serialize()
  65578. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65579. return FreeCameraGamepadInput;
  65580. }());
  65581. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65582. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65583. })(BABYLON || (BABYLON = {}));
  65584. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65585. "use strict";
  65586. var BABYLON;
  65587. (function (BABYLON) {
  65588. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65589. function ArcRotateCameraGamepadInput() {
  65590. this.gamepadRotationSensibility = 80;
  65591. this.gamepadMoveSensibility = 40;
  65592. }
  65593. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65594. var _this = this;
  65595. var manager = this.camera.getScene().gamepadManager;
  65596. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65597. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65598. // prioritize XBOX gamepads.
  65599. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65600. _this.gamepad = gamepad;
  65601. }
  65602. }
  65603. });
  65604. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65605. if (_this.gamepad === gamepad) {
  65606. _this.gamepad = null;
  65607. }
  65608. });
  65609. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65610. };
  65611. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65612. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65613. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65614. this.gamepad = null;
  65615. };
  65616. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65617. if (this.gamepad) {
  65618. var camera = this.camera;
  65619. var RSValues = this.gamepad.rightStick;
  65620. if (RSValues) {
  65621. if (RSValues.x != 0) {
  65622. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65623. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65624. camera.inertialAlphaOffset += normalizedRX;
  65625. }
  65626. }
  65627. if (RSValues.y != 0) {
  65628. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65629. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65630. camera.inertialBetaOffset += normalizedRY;
  65631. }
  65632. }
  65633. }
  65634. var LSValues = this.gamepad.leftStick;
  65635. if (LSValues && LSValues.y != 0) {
  65636. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65637. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65638. this.camera.inertialRadiusOffset -= normalizedLY;
  65639. }
  65640. }
  65641. }
  65642. };
  65643. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65644. return "ArcRotateCameraGamepadInput";
  65645. };
  65646. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65647. return "gamepad";
  65648. };
  65649. __decorate([
  65650. BABYLON.serialize()
  65651. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65652. __decorate([
  65653. BABYLON.serialize()
  65654. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65655. return ArcRotateCameraGamepadInput;
  65656. }());
  65657. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65658. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65659. })(BABYLON || (BABYLON = {}));
  65660. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65661. "use strict";
  65662. var BABYLON;
  65663. (function (BABYLON) {
  65664. var GamepadManager = /** @class */ (function () {
  65665. function GamepadManager(_scene) {
  65666. var _this = this;
  65667. this._scene = _scene;
  65668. this._babylonGamepads = [];
  65669. this._oneGamepadConnected = false;
  65670. this._isMonitoring = false;
  65671. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65672. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65673. this._gamepadEventSupported = false;
  65674. }
  65675. else {
  65676. this._gamepadEventSupported = 'GamepadEvent' in window;
  65677. this._gamepadSupport = (navigator.getGamepads ||
  65678. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65679. }
  65680. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65681. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65682. for (var i in _this._babylonGamepads) {
  65683. var gamepad = _this._babylonGamepads[i];
  65684. if (gamepad && gamepad._isConnected) {
  65685. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65686. }
  65687. }
  65688. });
  65689. this._onGamepadConnectedEvent = function (evt) {
  65690. var gamepad = evt.gamepad;
  65691. if (gamepad.index in _this._babylonGamepads) {
  65692. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65693. return;
  65694. }
  65695. }
  65696. var newGamepad;
  65697. if (_this._babylonGamepads[gamepad.index]) {
  65698. newGamepad = _this._babylonGamepads[gamepad.index];
  65699. newGamepad.browserGamepad = gamepad;
  65700. newGamepad._isConnected = true;
  65701. }
  65702. else {
  65703. newGamepad = _this._addNewGamepad(gamepad);
  65704. }
  65705. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65706. _this._startMonitoringGamepads();
  65707. };
  65708. this._onGamepadDisconnectedEvent = function (evt) {
  65709. var gamepad = evt.gamepad;
  65710. // Remove the gamepad from the list of gamepads to monitor.
  65711. for (var i in _this._babylonGamepads) {
  65712. if (_this._babylonGamepads[i].index === gamepad.index) {
  65713. var disconnectedGamepad = _this._babylonGamepads[i];
  65714. disconnectedGamepad._isConnected = false;
  65715. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65716. break;
  65717. }
  65718. }
  65719. };
  65720. if (this._gamepadSupport) {
  65721. //first add already-connected gamepads
  65722. this._updateGamepadObjects();
  65723. if (this._babylonGamepads.length) {
  65724. this._startMonitoringGamepads();
  65725. }
  65726. // Checking if the gamepad connected event is supported (like in Firefox)
  65727. if (this._gamepadEventSupported) {
  65728. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  65729. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  65730. }
  65731. else {
  65732. this._startMonitoringGamepads();
  65733. }
  65734. }
  65735. }
  65736. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  65737. get: function () {
  65738. return this._babylonGamepads;
  65739. },
  65740. enumerable: true,
  65741. configurable: true
  65742. });
  65743. GamepadManager.prototype.getGamepadByType = function (type) {
  65744. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  65745. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  65746. var gamepad = _a[_i];
  65747. if (gamepad && gamepad.type === type) {
  65748. return gamepad;
  65749. }
  65750. }
  65751. return null;
  65752. };
  65753. GamepadManager.prototype.dispose = function () {
  65754. if (this._gamepadEventSupported) {
  65755. if (this._onGamepadConnectedEvent) {
  65756. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  65757. }
  65758. if (this._onGamepadDisconnectedEvent) {
  65759. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  65760. }
  65761. this._onGamepadConnectedEvent = null;
  65762. this._onGamepadDisconnectedEvent = null;
  65763. }
  65764. this._babylonGamepads.forEach(function (gamepad) {
  65765. gamepad.dispose();
  65766. });
  65767. this.onGamepadConnectedObservable.clear();
  65768. this.onGamepadDisconnectedObservable.clear();
  65769. this._oneGamepadConnected = false;
  65770. this._stopMonitoringGamepads();
  65771. this._babylonGamepads = [];
  65772. };
  65773. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  65774. if (!this._oneGamepadConnected) {
  65775. this._oneGamepadConnected = true;
  65776. }
  65777. var newGamepad;
  65778. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  65779. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  65780. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  65781. }
  65782. else if (gamepad.pose) {
  65783. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65784. }
  65785. else {
  65786. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65787. }
  65788. this._babylonGamepads[newGamepad.index] = newGamepad;
  65789. return newGamepad;
  65790. };
  65791. GamepadManager.prototype._startMonitoringGamepads = function () {
  65792. if (!this._isMonitoring) {
  65793. this._isMonitoring = true;
  65794. //back-comp
  65795. if (!this._scene) {
  65796. this._checkGamepadsStatus();
  65797. }
  65798. }
  65799. };
  65800. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65801. this._isMonitoring = false;
  65802. };
  65803. GamepadManager.prototype._checkGamepadsStatus = function () {
  65804. var _this = this;
  65805. // Hack to be compatible Chrome
  65806. this._updateGamepadObjects();
  65807. for (var i in this._babylonGamepads) {
  65808. var gamepad = this._babylonGamepads[i];
  65809. if (!gamepad || !gamepad.isConnected) {
  65810. continue;
  65811. }
  65812. gamepad.update();
  65813. }
  65814. if (this._isMonitoring && !this._scene) {
  65815. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65816. }
  65817. };
  65818. // This function is called only on Chrome, which does not properly support
  65819. // connection/disconnection events and forces you to recopy again the gamepad object
  65820. GamepadManager.prototype._updateGamepadObjects = function () {
  65821. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65822. for (var i = 0; i < gamepads.length; i++) {
  65823. if (gamepads[i]) {
  65824. if (!this._babylonGamepads[gamepads[i].index]) {
  65825. var newGamepad = this._addNewGamepad(gamepads[i]);
  65826. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65827. }
  65828. else {
  65829. // Forced to copy again this object for Chrome for unknown reason
  65830. this._babylonGamepads[i].browserGamepad = gamepads[i];
  65831. if (!this._babylonGamepads[i].isConnected) {
  65832. this._babylonGamepads[i]._isConnected = true;
  65833. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  65834. }
  65835. }
  65836. }
  65837. }
  65838. };
  65839. return GamepadManager;
  65840. }());
  65841. BABYLON.GamepadManager = GamepadManager;
  65842. })(BABYLON || (BABYLON = {}));
  65843. //# sourceMappingURL=babylon.gamepadManager.js.map
  65844. "use strict";
  65845. var BABYLON;
  65846. (function (BABYLON) {
  65847. var StickValues = /** @class */ (function () {
  65848. function StickValues(x, y) {
  65849. this.x = x;
  65850. this.y = y;
  65851. }
  65852. return StickValues;
  65853. }());
  65854. BABYLON.StickValues = StickValues;
  65855. var Gamepad = /** @class */ (function () {
  65856. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  65857. if (leftStickX === void 0) { leftStickX = 0; }
  65858. if (leftStickY === void 0) { leftStickY = 1; }
  65859. if (rightStickX === void 0) { rightStickX = 2; }
  65860. if (rightStickY === void 0) { rightStickY = 3; }
  65861. this.id = id;
  65862. this.index = index;
  65863. this.browserGamepad = browserGamepad;
  65864. this._isConnected = true;
  65865. this._invertLeftStickY = false;
  65866. this.type = Gamepad.GAMEPAD;
  65867. this._leftStickAxisX = leftStickX;
  65868. this._leftStickAxisY = leftStickY;
  65869. this._rightStickAxisX = rightStickX;
  65870. this._rightStickAxisY = rightStickY;
  65871. if (this.browserGamepad.axes.length >= 2) {
  65872. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65873. }
  65874. if (this.browserGamepad.axes.length >= 4) {
  65875. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65876. }
  65877. }
  65878. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65879. get: function () {
  65880. return this._isConnected;
  65881. },
  65882. enumerable: true,
  65883. configurable: true
  65884. });
  65885. Gamepad.prototype.onleftstickchanged = function (callback) {
  65886. this._onleftstickchanged = callback;
  65887. };
  65888. Gamepad.prototype.onrightstickchanged = function (callback) {
  65889. this._onrightstickchanged = callback;
  65890. };
  65891. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65892. get: function () {
  65893. return this._leftStick;
  65894. },
  65895. set: function (newValues) {
  65896. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65897. this._onleftstickchanged(newValues);
  65898. }
  65899. this._leftStick = newValues;
  65900. },
  65901. enumerable: true,
  65902. configurable: true
  65903. });
  65904. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65905. get: function () {
  65906. return this._rightStick;
  65907. },
  65908. set: function (newValues) {
  65909. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65910. this._onrightstickchanged(newValues);
  65911. }
  65912. this._rightStick = newValues;
  65913. },
  65914. enumerable: true,
  65915. configurable: true
  65916. });
  65917. Gamepad.prototype.update = function () {
  65918. if (this._leftStick) {
  65919. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65920. if (this._invertLeftStickY) {
  65921. this.leftStick.y *= -1;
  65922. }
  65923. }
  65924. if (this._rightStick) {
  65925. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65926. }
  65927. };
  65928. Gamepad.prototype.dispose = function () {
  65929. };
  65930. Gamepad.GAMEPAD = 0;
  65931. Gamepad.GENERIC = 1;
  65932. Gamepad.XBOX = 2;
  65933. Gamepad.POSE_ENABLED = 3;
  65934. return Gamepad;
  65935. }());
  65936. BABYLON.Gamepad = Gamepad;
  65937. var GenericPad = /** @class */ (function (_super) {
  65938. __extends(GenericPad, _super);
  65939. function GenericPad(id, index, browserGamepad) {
  65940. var _this = _super.call(this, id, index, browserGamepad) || this;
  65941. _this.onButtonDownObservable = new BABYLON.Observable();
  65942. _this.onButtonUpObservable = new BABYLON.Observable();
  65943. _this.type = Gamepad.GENERIC;
  65944. _this._buttons = new Array(browserGamepad.buttons.length);
  65945. return _this;
  65946. }
  65947. GenericPad.prototype.onbuttondown = function (callback) {
  65948. this._onbuttondown = callback;
  65949. };
  65950. GenericPad.prototype.onbuttonup = function (callback) {
  65951. this._onbuttonup = callback;
  65952. };
  65953. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65954. if (newValue !== currentValue) {
  65955. if (newValue === 1) {
  65956. if (this._onbuttondown) {
  65957. this._onbuttondown(buttonIndex);
  65958. }
  65959. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65960. }
  65961. if (newValue === 0) {
  65962. if (this._onbuttonup) {
  65963. this._onbuttonup(buttonIndex);
  65964. }
  65965. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65966. }
  65967. }
  65968. return newValue;
  65969. };
  65970. GenericPad.prototype.update = function () {
  65971. _super.prototype.update.call(this);
  65972. for (var index = 0; index < this._buttons.length; index++) {
  65973. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65974. }
  65975. };
  65976. GenericPad.prototype.dispose = function () {
  65977. _super.prototype.dispose.call(this);
  65978. this.onButtonDownObservable.clear();
  65979. this.onButtonUpObservable.clear();
  65980. };
  65981. return GenericPad;
  65982. }(Gamepad));
  65983. BABYLON.GenericPad = GenericPad;
  65984. })(BABYLON || (BABYLON = {}));
  65985. //# sourceMappingURL=babylon.gamepad.js.map
  65986. "use strict";
  65987. var BABYLON;
  65988. (function (BABYLON) {
  65989. var Xbox360Button;
  65990. (function (Xbox360Button) {
  65991. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65992. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65993. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65994. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65995. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65996. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65997. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65998. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65999. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  66000. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  66001. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  66002. var Xbox360Dpad;
  66003. (function (Xbox360Dpad) {
  66004. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  66005. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  66006. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  66007. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  66008. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  66009. var Xbox360Pad = /** @class */ (function (_super) {
  66010. __extends(Xbox360Pad, _super);
  66011. function Xbox360Pad(id, index, gamepad, xboxOne) {
  66012. if (xboxOne === void 0) { xboxOne = false; }
  66013. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  66014. _this._leftTrigger = 0;
  66015. _this._rightTrigger = 0;
  66016. _this.onButtonDownObservable = new BABYLON.Observable();
  66017. _this.onButtonUpObservable = new BABYLON.Observable();
  66018. _this.onPadDownObservable = new BABYLON.Observable();
  66019. _this.onPadUpObservable = new BABYLON.Observable();
  66020. _this._buttonA = 0;
  66021. _this._buttonB = 0;
  66022. _this._buttonX = 0;
  66023. _this._buttonY = 0;
  66024. _this._buttonBack = 0;
  66025. _this._buttonStart = 0;
  66026. _this._buttonLB = 0;
  66027. _this._buttonRB = 0;
  66028. _this._buttonLeftStick = 0;
  66029. _this._buttonRightStick = 0;
  66030. _this._dPadUp = 0;
  66031. _this._dPadDown = 0;
  66032. _this._dPadLeft = 0;
  66033. _this._dPadRight = 0;
  66034. _this._isXboxOnePad = false;
  66035. _this.type = BABYLON.Gamepad.XBOX;
  66036. _this._isXboxOnePad = xboxOne;
  66037. return _this;
  66038. }
  66039. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  66040. this._onlefttriggerchanged = callback;
  66041. };
  66042. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  66043. this._onrighttriggerchanged = callback;
  66044. };
  66045. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  66046. get: function () {
  66047. return this._leftTrigger;
  66048. },
  66049. set: function (newValue) {
  66050. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66051. this._onlefttriggerchanged(newValue);
  66052. }
  66053. this._leftTrigger = newValue;
  66054. },
  66055. enumerable: true,
  66056. configurable: true
  66057. });
  66058. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66059. get: function () {
  66060. return this._rightTrigger;
  66061. },
  66062. set: function (newValue) {
  66063. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66064. this._onrighttriggerchanged(newValue);
  66065. }
  66066. this._rightTrigger = newValue;
  66067. },
  66068. enumerable: true,
  66069. configurable: true
  66070. });
  66071. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66072. this._onbuttondown = callback;
  66073. };
  66074. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66075. this._onbuttonup = callback;
  66076. };
  66077. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66078. this._ondpaddown = callback;
  66079. };
  66080. Xbox360Pad.prototype.ondpadup = function (callback) {
  66081. this._ondpadup = callback;
  66082. };
  66083. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66084. if (newValue !== currentValue) {
  66085. if (newValue === 1) {
  66086. if (this._onbuttondown) {
  66087. this._onbuttondown(buttonType);
  66088. }
  66089. this.onButtonDownObservable.notifyObservers(buttonType);
  66090. }
  66091. if (newValue === 0) {
  66092. if (this._onbuttonup) {
  66093. this._onbuttonup(buttonType);
  66094. }
  66095. this.onButtonUpObservable.notifyObservers(buttonType);
  66096. }
  66097. }
  66098. return newValue;
  66099. };
  66100. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66101. if (newValue !== currentValue) {
  66102. if (newValue === 1) {
  66103. if (this._ondpaddown) {
  66104. this._ondpaddown(buttonType);
  66105. }
  66106. this.onPadDownObservable.notifyObservers(buttonType);
  66107. }
  66108. if (newValue === 0) {
  66109. if (this._ondpadup) {
  66110. this._ondpadup(buttonType);
  66111. }
  66112. this.onPadUpObservable.notifyObservers(buttonType);
  66113. }
  66114. }
  66115. return newValue;
  66116. };
  66117. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66118. get: function () {
  66119. return this._buttonA;
  66120. },
  66121. set: function (value) {
  66122. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66123. },
  66124. enumerable: true,
  66125. configurable: true
  66126. });
  66127. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66128. get: function () {
  66129. return this._buttonB;
  66130. },
  66131. set: function (value) {
  66132. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66133. },
  66134. enumerable: true,
  66135. configurable: true
  66136. });
  66137. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66138. get: function () {
  66139. return this._buttonX;
  66140. },
  66141. set: function (value) {
  66142. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66143. },
  66144. enumerable: true,
  66145. configurable: true
  66146. });
  66147. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66148. get: function () {
  66149. return this._buttonY;
  66150. },
  66151. set: function (value) {
  66152. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66153. },
  66154. enumerable: true,
  66155. configurable: true
  66156. });
  66157. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66158. get: function () {
  66159. return this._buttonStart;
  66160. },
  66161. set: function (value) {
  66162. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66163. },
  66164. enumerable: true,
  66165. configurable: true
  66166. });
  66167. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66168. get: function () {
  66169. return this._buttonBack;
  66170. },
  66171. set: function (value) {
  66172. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66173. },
  66174. enumerable: true,
  66175. configurable: true
  66176. });
  66177. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66178. get: function () {
  66179. return this._buttonLB;
  66180. },
  66181. set: function (value) {
  66182. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66183. },
  66184. enumerable: true,
  66185. configurable: true
  66186. });
  66187. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66188. get: function () {
  66189. return this._buttonRB;
  66190. },
  66191. set: function (value) {
  66192. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66193. },
  66194. enumerable: true,
  66195. configurable: true
  66196. });
  66197. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66198. get: function () {
  66199. return this._buttonLeftStick;
  66200. },
  66201. set: function (value) {
  66202. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66203. },
  66204. enumerable: true,
  66205. configurable: true
  66206. });
  66207. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66208. get: function () {
  66209. return this._buttonRightStick;
  66210. },
  66211. set: function (value) {
  66212. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66213. },
  66214. enumerable: true,
  66215. configurable: true
  66216. });
  66217. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66218. get: function () {
  66219. return this._dPadUp;
  66220. },
  66221. set: function (value) {
  66222. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66223. },
  66224. enumerable: true,
  66225. configurable: true
  66226. });
  66227. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66228. get: function () {
  66229. return this._dPadDown;
  66230. },
  66231. set: function (value) {
  66232. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66233. },
  66234. enumerable: true,
  66235. configurable: true
  66236. });
  66237. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66238. get: function () {
  66239. return this._dPadLeft;
  66240. },
  66241. set: function (value) {
  66242. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66243. },
  66244. enumerable: true,
  66245. configurable: true
  66246. });
  66247. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66248. get: function () {
  66249. return this._dPadRight;
  66250. },
  66251. set: function (value) {
  66252. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66253. },
  66254. enumerable: true,
  66255. configurable: true
  66256. });
  66257. Xbox360Pad.prototype.update = function () {
  66258. _super.prototype.update.call(this);
  66259. if (this._isXboxOnePad) {
  66260. this.buttonA = this.browserGamepad.buttons[0].value;
  66261. this.buttonB = this.browserGamepad.buttons[1].value;
  66262. this.buttonX = this.browserGamepad.buttons[2].value;
  66263. this.buttonY = this.browserGamepad.buttons[3].value;
  66264. this.buttonLB = this.browserGamepad.buttons[4].value;
  66265. this.buttonRB = this.browserGamepad.buttons[5].value;
  66266. this.leftTrigger = this.browserGamepad.axes[2];
  66267. this.rightTrigger = this.browserGamepad.axes[5];
  66268. this.buttonBack = this.browserGamepad.buttons[9].value;
  66269. this.buttonStart = this.browserGamepad.buttons[8].value;
  66270. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66271. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66272. this.dPadUp = this.browserGamepad.buttons[11].value;
  66273. this.dPadDown = this.browserGamepad.buttons[12].value;
  66274. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66275. this.dPadRight = this.browserGamepad.buttons[14].value;
  66276. }
  66277. else {
  66278. this.buttonA = this.browserGamepad.buttons[0].value;
  66279. this.buttonB = this.browserGamepad.buttons[1].value;
  66280. this.buttonX = this.browserGamepad.buttons[2].value;
  66281. this.buttonY = this.browserGamepad.buttons[3].value;
  66282. this.buttonLB = this.browserGamepad.buttons[4].value;
  66283. this.buttonRB = this.browserGamepad.buttons[5].value;
  66284. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66285. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66286. this.buttonBack = this.browserGamepad.buttons[8].value;
  66287. this.buttonStart = this.browserGamepad.buttons[9].value;
  66288. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66289. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66290. this.dPadUp = this.browserGamepad.buttons[12].value;
  66291. this.dPadDown = this.browserGamepad.buttons[13].value;
  66292. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66293. this.dPadRight = this.browserGamepad.buttons[15].value;
  66294. }
  66295. };
  66296. Xbox360Pad.prototype.dispose = function () {
  66297. _super.prototype.dispose.call(this);
  66298. this.onButtonDownObservable.clear();
  66299. this.onButtonUpObservable.clear();
  66300. this.onPadDownObservable.clear();
  66301. this.onPadUpObservable.clear();
  66302. };
  66303. return Xbox360Pad;
  66304. }(BABYLON.Gamepad));
  66305. BABYLON.Xbox360Pad = Xbox360Pad;
  66306. })(BABYLON || (BABYLON = {}));
  66307. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66308. "use strict";
  66309. var BABYLON;
  66310. (function (BABYLON) {
  66311. var PoseEnabledControllerType;
  66312. (function (PoseEnabledControllerType) {
  66313. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66314. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66315. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66316. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66317. /**
  66318. * Google Daydream
  66319. */
  66320. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66321. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66322. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66323. var PoseEnabledControllerHelper = /** @class */ (function () {
  66324. function PoseEnabledControllerHelper() {
  66325. }
  66326. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66327. // Oculus Touch
  66328. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66329. return new BABYLON.OculusTouchController(vrGamepad);
  66330. }
  66331. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66332. return new BABYLON.WindowsMotionController(vrGamepad);
  66333. }
  66334. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66335. return new BABYLON.ViveController(vrGamepad);
  66336. }
  66337. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66338. return new BABYLON.GearVRController(vrGamepad);
  66339. }
  66340. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66341. return new BABYLON.DaydreamController(vrGamepad);
  66342. }
  66343. else {
  66344. return new BABYLON.GenericController(vrGamepad);
  66345. }
  66346. };
  66347. return PoseEnabledControllerHelper;
  66348. }());
  66349. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66350. var PoseEnabledController = /** @class */ (function (_super) {
  66351. __extends(PoseEnabledController, _super);
  66352. function PoseEnabledController(browserGamepad) {
  66353. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66354. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66355. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66356. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66357. // Represents device position and rotation in babylon space
  66358. _this.devicePosition = BABYLON.Vector3.Zero();
  66359. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66360. _this.deviceScaleFactor = 1;
  66361. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66362. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66363. /**
  66364. * Node to be used when casting a ray from the controller
  66365. */
  66366. _this._pointingPoseNode = null;
  66367. _this._workingMatrix = BABYLON.Matrix.Identity();
  66368. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66369. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66370. _this.position = BABYLON.Vector3.Zero();
  66371. _this.rotationQuaternion = new BABYLON.Quaternion();
  66372. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66373. _this._calculatedRotation = new BABYLON.Quaternion();
  66374. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66375. return _this;
  66376. }
  66377. PoseEnabledController.prototype.update = function () {
  66378. _super.prototype.update.call(this);
  66379. var pose = this.browserGamepad.pose;
  66380. this.updateFromDevice(pose);
  66381. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66382. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66383. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66384. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66385. if (this._mesh) {
  66386. this._mesh.position.copyFrom(this.devicePosition);
  66387. if (this._mesh.rotationQuaternion) {
  66388. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66389. }
  66390. }
  66391. };
  66392. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66393. if (poseData) {
  66394. this.rawPose = poseData;
  66395. if (poseData.position) {
  66396. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66397. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66398. this._deviceRoomPosition.z *= -1;
  66399. }
  66400. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66401. this._calculatedPosition.addInPlace(this.position);
  66402. }
  66403. var pose = this.rawPose;
  66404. if (poseData.orientation && pose.orientation) {
  66405. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66406. if (this._mesh) {
  66407. if (this._mesh.getScene().useRightHandedSystem) {
  66408. this._deviceRoomRotationQuaternion.z *= -1;
  66409. this._deviceRoomRotationQuaternion.w *= -1;
  66410. }
  66411. else {
  66412. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66413. }
  66414. }
  66415. // if the camera is set, rotate to the camera's rotation
  66416. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66417. }
  66418. }
  66419. };
  66420. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66421. if (this._mesh) {
  66422. this._mesh.parent = null;
  66423. }
  66424. this._mesh = mesh;
  66425. if (this._poseControlledCamera) {
  66426. this._mesh.parent = this._poseControlledCamera;
  66427. }
  66428. if (!this._mesh.rotationQuaternion) {
  66429. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66430. }
  66431. };
  66432. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66433. this._poseControlledCamera = camera;
  66434. if (this._mesh) {
  66435. this._mesh.parent = this._poseControlledCamera;
  66436. }
  66437. };
  66438. PoseEnabledController.prototype.dispose = function () {
  66439. if (this._mesh) {
  66440. this._mesh.dispose();
  66441. }
  66442. this._mesh = null;
  66443. _super.prototype.dispose.call(this);
  66444. };
  66445. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66446. get: function () {
  66447. return this._mesh;
  66448. },
  66449. enumerable: true,
  66450. configurable: true
  66451. });
  66452. PoseEnabledController.prototype.getForwardRay = function (length) {
  66453. if (length === void 0) { length = 100; }
  66454. if (!this.mesh) {
  66455. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66456. }
  66457. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66458. var origin = m.getTranslation();
  66459. var forward = new BABYLON.Vector3(0, 0, -1);
  66460. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66461. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66462. return new BABYLON.Ray(origin, direction, length);
  66463. };
  66464. /**
  66465. * Name of the child mesh that can be used to cast a ray from the controller
  66466. */
  66467. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66468. return PoseEnabledController;
  66469. }(BABYLON.Gamepad));
  66470. BABYLON.PoseEnabledController = PoseEnabledController;
  66471. })(BABYLON || (BABYLON = {}));
  66472. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66473. "use strict";
  66474. var BABYLON;
  66475. (function (BABYLON) {
  66476. var WebVRController = /** @class */ (function (_super) {
  66477. __extends(WebVRController, _super);
  66478. function WebVRController(vrGamepad) {
  66479. var _this = _super.call(this, vrGamepad) || this;
  66480. // Observables
  66481. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66482. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66483. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66484. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66485. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66486. _this.pad = { x: 0, y: 0 };
  66487. // avoid GC, store state in a tmp object
  66488. _this._changes = {
  66489. pressChanged: false,
  66490. touchChanged: false,
  66491. valueChanged: false,
  66492. changed: false
  66493. };
  66494. _this._buttons = new Array(vrGamepad.buttons.length);
  66495. _this.hand = vrGamepad.hand;
  66496. return _this;
  66497. }
  66498. WebVRController.prototype.onButtonStateChange = function (callback) {
  66499. this._onButtonStateChange = callback;
  66500. };
  66501. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66502. get: function () {
  66503. return this._defaultModel;
  66504. },
  66505. enumerable: true,
  66506. configurable: true
  66507. });
  66508. WebVRController.prototype.update = function () {
  66509. _super.prototype.update.call(this);
  66510. for (var index = 0; index < this._buttons.length; index++) {
  66511. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66512. }
  66513. ;
  66514. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66515. this.pad.x = this.leftStick.x;
  66516. this.pad.y = this.leftStick.y;
  66517. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66518. }
  66519. };
  66520. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66521. if (!newState) {
  66522. newState = {
  66523. pressed: false,
  66524. touched: false,
  66525. value: 0
  66526. };
  66527. }
  66528. if (!currentState) {
  66529. this._buttons[buttonIndex] = {
  66530. pressed: newState.pressed,
  66531. touched: newState.touched,
  66532. value: newState.value
  66533. };
  66534. return;
  66535. }
  66536. this._checkChanges(newState, currentState);
  66537. if (this._changes.changed) {
  66538. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66539. this._handleButtonChange(buttonIndex, newState, this._changes);
  66540. }
  66541. this._buttons[buttonIndex].pressed = newState.pressed;
  66542. this._buttons[buttonIndex].touched = newState.touched;
  66543. // oculus triggers are never 0, thou not touched.
  66544. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66545. };
  66546. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66547. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66548. this._changes.touchChanged = newState.touched !== currentState.touched;
  66549. this._changes.valueChanged = newState.value !== currentState.value;
  66550. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66551. return this._changes;
  66552. };
  66553. WebVRController.prototype.dispose = function () {
  66554. _super.prototype.dispose.call(this);
  66555. this.onTriggerStateChangedObservable.clear();
  66556. this.onMainButtonStateChangedObservable.clear();
  66557. this.onSecondaryButtonStateChangedObservable.clear();
  66558. this.onPadStateChangedObservable.clear();
  66559. this.onPadValuesChangedObservable.clear();
  66560. };
  66561. return WebVRController;
  66562. }(BABYLON.PoseEnabledController));
  66563. BABYLON.WebVRController = WebVRController;
  66564. })(BABYLON || (BABYLON = {}));
  66565. //# sourceMappingURL=babylon.webVRController.js.map
  66566. "use strict";
  66567. var BABYLON;
  66568. (function (BABYLON) {
  66569. var OculusTouchController = /** @class */ (function (_super) {
  66570. __extends(OculusTouchController, _super);
  66571. function OculusTouchController(vrGamepad) {
  66572. var _this = _super.call(this, vrGamepad) || this;
  66573. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66574. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66575. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66576. return _this;
  66577. }
  66578. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66579. var _this = this;
  66580. var meshName;
  66581. // Hand
  66582. if (this.hand === 'left') {
  66583. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66584. }
  66585. else {
  66586. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66587. }
  66588. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66589. /*
  66590. Parent Mesh name: oculus_touch_left
  66591. - body
  66592. - trigger
  66593. - thumbstick
  66594. - grip
  66595. - button_y
  66596. - button_x
  66597. - button_enter
  66598. */
  66599. _this._defaultModel = newMeshes[1];
  66600. _this.attachToMesh(_this._defaultModel);
  66601. if (meshLoaded) {
  66602. meshLoaded(_this._defaultModel);
  66603. }
  66604. });
  66605. };
  66606. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66607. // helper getters for left and right hand.
  66608. get: function () {
  66609. if (this.hand === 'right') {
  66610. return this.onMainButtonStateChangedObservable;
  66611. }
  66612. else {
  66613. throw new Error('No A button on left hand');
  66614. }
  66615. },
  66616. enumerable: true,
  66617. configurable: true
  66618. });
  66619. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66620. get: function () {
  66621. if (this.hand === 'right') {
  66622. return this.onSecondaryButtonStateChangedObservable;
  66623. }
  66624. else {
  66625. throw new Error('No B button on left hand');
  66626. }
  66627. },
  66628. enumerable: true,
  66629. configurable: true
  66630. });
  66631. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66632. get: function () {
  66633. if (this.hand === 'left') {
  66634. return this.onMainButtonStateChangedObservable;
  66635. }
  66636. else {
  66637. throw new Error('No X button on right hand');
  66638. }
  66639. },
  66640. enumerable: true,
  66641. configurable: true
  66642. });
  66643. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66644. get: function () {
  66645. if (this.hand === 'left') {
  66646. return this.onSecondaryButtonStateChangedObservable;
  66647. }
  66648. else {
  66649. throw new Error('No Y button on right hand');
  66650. }
  66651. },
  66652. enumerable: true,
  66653. configurable: true
  66654. });
  66655. /*
  66656. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66657. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66658. 2) secondary trigger (same)
  66659. 3) A (right) X (left), touch, pressed = value
  66660. 4) B / Y
  66661. 5) thumb rest
  66662. */
  66663. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66664. var notifyObject = state; //{ state: state, changes: changes };
  66665. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66666. switch (buttonIdx) {
  66667. case 0:
  66668. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66669. return;
  66670. case 1:// index trigger
  66671. if (this._defaultModel) {
  66672. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66673. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66674. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66675. }
  66676. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66677. return;
  66678. case 2:// secondary trigger
  66679. if (this._defaultModel) {
  66680. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66681. }
  66682. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66683. return;
  66684. case 3:
  66685. if (this._defaultModel) {
  66686. if (notifyObject.pressed) {
  66687. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66688. }
  66689. else {
  66690. (this._defaultModel.getChildren()[1]).position.y = 0;
  66691. }
  66692. }
  66693. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66694. return;
  66695. case 4:
  66696. if (this._defaultModel) {
  66697. if (notifyObject.pressed) {
  66698. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66699. }
  66700. else {
  66701. (this._defaultModel.getChildren()[2]).position.y = 0;
  66702. }
  66703. }
  66704. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66705. return;
  66706. case 5:
  66707. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66708. return;
  66709. }
  66710. };
  66711. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66712. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66713. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66714. return OculusTouchController;
  66715. }(BABYLON.WebVRController));
  66716. BABYLON.OculusTouchController = OculusTouchController;
  66717. })(BABYLON || (BABYLON = {}));
  66718. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66719. "use strict";
  66720. var BABYLON;
  66721. (function (BABYLON) {
  66722. var ViveController = /** @class */ (function (_super) {
  66723. __extends(ViveController, _super);
  66724. function ViveController(vrGamepad) {
  66725. var _this = _super.call(this, vrGamepad) || this;
  66726. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66727. _this._invertLeftStickY = true;
  66728. return _this;
  66729. }
  66730. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66731. var _this = this;
  66732. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  66733. /*
  66734. Parent Mesh name: ViveWand
  66735. - body
  66736. - r_gripper
  66737. - l_gripper
  66738. - menu_button
  66739. - system_button
  66740. - trackpad
  66741. - trigger
  66742. - LED
  66743. */
  66744. _this._defaultModel = newMeshes[1];
  66745. _this.attachToMesh(_this._defaultModel);
  66746. if (meshLoaded) {
  66747. meshLoaded(_this._defaultModel);
  66748. }
  66749. });
  66750. };
  66751. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  66752. get: function () {
  66753. return this.onMainButtonStateChangedObservable;
  66754. },
  66755. enumerable: true,
  66756. configurable: true
  66757. });
  66758. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  66759. get: function () {
  66760. return this.onMainButtonStateChangedObservable;
  66761. },
  66762. enumerable: true,
  66763. configurable: true
  66764. });
  66765. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  66766. get: function () {
  66767. return this.onSecondaryButtonStateChangedObservable;
  66768. },
  66769. enumerable: true,
  66770. configurable: true
  66771. });
  66772. /**
  66773. * Vive mapping:
  66774. * 0: touchpad
  66775. * 1: trigger
  66776. * 2: left AND right buttons
  66777. * 3: menu button
  66778. */
  66779. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66780. var notifyObject = state; //{ state: state, changes: changes };
  66781. switch (buttonIdx) {
  66782. case 0:
  66783. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66784. return;
  66785. case 1:// index trigger
  66786. if (this._defaultModel) {
  66787. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66788. }
  66789. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66790. return;
  66791. case 2:// left AND right button
  66792. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66793. return;
  66794. case 3:
  66795. if (this._defaultModel) {
  66796. if (notifyObject.pressed) {
  66797. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66798. }
  66799. else {
  66800. (this._defaultModel.getChildren()[2]).position.y = 0;
  66801. }
  66802. }
  66803. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66804. return;
  66805. }
  66806. };
  66807. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66808. ViveController.MODEL_FILENAME = 'wand.babylon';
  66809. return ViveController;
  66810. }(BABYLON.WebVRController));
  66811. BABYLON.ViveController = ViveController;
  66812. })(BABYLON || (BABYLON = {}));
  66813. //# sourceMappingURL=babylon.viveController.js.map
  66814. "use strict";
  66815. var BABYLON;
  66816. (function (BABYLON) {
  66817. var GenericController = /** @class */ (function (_super) {
  66818. __extends(GenericController, _super);
  66819. function GenericController(vrGamepad) {
  66820. return _super.call(this, vrGamepad) || this;
  66821. }
  66822. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66823. var _this = this;
  66824. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66825. _this._defaultModel = newMeshes[1];
  66826. _this.attachToMesh(_this._defaultModel);
  66827. if (meshLoaded) {
  66828. meshLoaded(_this._defaultModel);
  66829. }
  66830. });
  66831. };
  66832. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66833. console.log("Button id: " + buttonIdx + "state: ");
  66834. console.dir(state);
  66835. };
  66836. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66837. GenericController.MODEL_FILENAME = 'generic.babylon';
  66838. return GenericController;
  66839. }(BABYLON.WebVRController));
  66840. BABYLON.GenericController = GenericController;
  66841. })(BABYLON || (BABYLON = {}));
  66842. //# sourceMappingURL=babylon.genericController.js.map
  66843. "use strict";
  66844. var BABYLON;
  66845. (function (BABYLON) {
  66846. var LoadedMeshInfo = /** @class */ (function () {
  66847. function LoadedMeshInfo() {
  66848. this.buttonMeshes = {};
  66849. this.axisMeshes = {};
  66850. }
  66851. return LoadedMeshInfo;
  66852. }());
  66853. var WindowsMotionController = /** @class */ (function (_super) {
  66854. __extends(WindowsMotionController, _super);
  66855. function WindowsMotionController(vrGamepad) {
  66856. var _this = _super.call(this, vrGamepad) || this;
  66857. _this._mapping = {
  66858. // Semantic button names
  66859. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  66860. // A mapping of the button name to glTF model node name
  66861. // that should be transformed by button value.
  66862. buttonMeshNames: {
  66863. 'trigger': 'SELECT',
  66864. 'menu': 'MENU',
  66865. 'grip': 'GRASP',
  66866. 'thumbstick': 'THUMBSTICK_PRESS',
  66867. 'trackpad': 'TOUCHPAD_PRESS'
  66868. },
  66869. // This mapping is used to translate from the Motion Controller to Babylon semantics
  66870. buttonObservableNames: {
  66871. 'trigger': 'onTriggerStateChangedObservable',
  66872. 'menu': 'onSecondaryButtonStateChangedObservable',
  66873. 'grip': 'onMainButtonStateChangedObservable',
  66874. 'thumbstick': 'onPadStateChangedObservable',
  66875. 'trackpad': 'onTrackpadChangedObservable'
  66876. },
  66877. // A mapping of the axis name to glTF model node name
  66878. // that should be transformed by axis value.
  66879. // This array mirrors the browserGamepad.axes array, such that
  66880. // the mesh corresponding to axis 0 is in this array index 0.
  66881. axisMeshNames: [
  66882. 'THUMBSTICK_X',
  66883. 'THUMBSTICK_Y',
  66884. 'TOUCHPAD_TOUCH_X',
  66885. 'TOUCHPAD_TOUCH_Y'
  66886. ],
  66887. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66888. };
  66889. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66890. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66891. _this.trackpad = { x: 0, y: 0 };
  66892. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66893. _this._loadedMeshInfo = null;
  66894. return _this;
  66895. }
  66896. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66897. get: function () {
  66898. return this.onTriggerStateChangedObservable;
  66899. },
  66900. enumerable: true,
  66901. configurable: true
  66902. });
  66903. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66904. get: function () {
  66905. return this.onSecondaryButtonStateChangedObservable;
  66906. },
  66907. enumerable: true,
  66908. configurable: true
  66909. });
  66910. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66911. get: function () {
  66912. return this.onMainButtonStateChangedObservable;
  66913. },
  66914. enumerable: true,
  66915. configurable: true
  66916. });
  66917. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66918. get: function () {
  66919. return this.onPadStateChangedObservable;
  66920. },
  66921. enumerable: true,
  66922. configurable: true
  66923. });
  66924. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66925. get: function () {
  66926. return this.onTrackpadChangedObservable;
  66927. },
  66928. enumerable: true,
  66929. configurable: true
  66930. });
  66931. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66932. get: function () {
  66933. return this.onTrackpadValuesChangedObservable;
  66934. },
  66935. enumerable: true,
  66936. configurable: true
  66937. });
  66938. /**
  66939. * Called once per frame by the engine.
  66940. */
  66941. WindowsMotionController.prototype.update = function () {
  66942. _super.prototype.update.call(this);
  66943. if (this.browserGamepad.axes) {
  66944. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66945. this.trackpad.x = this.browserGamepad["axes"][2];
  66946. this.trackpad.y = this.browserGamepad["axes"][3];
  66947. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66948. }
  66949. // Only need to animate axes if there is a loaded mesh
  66950. if (this._loadedMeshInfo) {
  66951. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66952. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66953. }
  66954. }
  66955. }
  66956. };
  66957. /**
  66958. * Called once for each button that changed state since the last frame
  66959. * @param buttonIdx Which button index changed
  66960. * @param state New state of the button
  66961. * @param changes Which properties on the state changed since last frame
  66962. */
  66963. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66964. var buttonName = this._mapping.buttons[buttonIdx];
  66965. if (!buttonName) {
  66966. return;
  66967. }
  66968. // Only emit events for buttons that we know how to map from index to name
  66969. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66970. if (observable) {
  66971. observable.notifyObservers(state);
  66972. }
  66973. this.lerpButtonTransform(buttonName, state.value);
  66974. };
  66975. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66976. // If there is no loaded mesh, there is nothing to transform.
  66977. if (!this._loadedMeshInfo) {
  66978. return;
  66979. }
  66980. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66981. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66982. return;
  66983. }
  66984. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66985. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66986. };
  66987. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66988. if (!this._loadedMeshInfo) {
  66989. return;
  66990. }
  66991. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66992. if (!meshInfo) {
  66993. return;
  66994. }
  66995. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66996. return;
  66997. }
  66998. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66999. var lerpValue = axisValue * 0.5 + 0.5;
  67000. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  67001. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  67002. };
  67003. /**
  67004. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  67005. * @param scene scene in which to add meshes
  67006. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  67007. */
  67008. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  67009. var _this = this;
  67010. if (forceDefault === void 0) { forceDefault = false; }
  67011. var path;
  67012. var filename;
  67013. // Checking if GLB loader is present
  67014. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  67015. // Determine the device specific folder based on the ID suffix
  67016. var device = 'default';
  67017. if (this.id && !forceDefault) {
  67018. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  67019. device = ((match && match[0]) || device);
  67020. }
  67021. // Hand
  67022. if (this.hand === 'left') {
  67023. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  67024. }
  67025. else {
  67026. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  67027. }
  67028. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  67029. }
  67030. else {
  67031. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  67032. path = BABYLON.GenericController.MODEL_BASE_URL;
  67033. filename = BABYLON.GenericController.MODEL_FILENAME;
  67034. }
  67035. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  67036. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  67037. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  67038. if (!_this._loadedMeshInfo) {
  67039. return;
  67040. }
  67041. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  67042. _this.attachToMesh(_this._defaultModel);
  67043. if (meshLoaded) {
  67044. meshLoaded(_this._defaultModel);
  67045. }
  67046. }, null, function (scene, message) {
  67047. BABYLON.Tools.Log(message);
  67048. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67049. if (!forceDefault) {
  67050. _this.initControllerMesh(scene, meshLoaded, true);
  67051. }
  67052. });
  67053. };
  67054. /**
  67055. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67056. * can be transformed by button presses and axes values, based on this._mapping.
  67057. *
  67058. * @param scene scene in which the meshes exist
  67059. * @param meshes list of meshes that make up the controller model to process
  67060. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67061. */
  67062. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67063. var loadedMeshInfo = null;
  67064. // Create a new mesh to contain the glTF hierarchy
  67065. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67066. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67067. var childMesh = null;
  67068. for (var i = 0; i < meshes.length; i++) {
  67069. var mesh = meshes[i];
  67070. if (!mesh.parent) {
  67071. // Exclude controller meshes from picking results
  67072. mesh.isPickable = false;
  67073. // Handle root node, attach to the new parentMesh
  67074. childMesh = mesh;
  67075. break;
  67076. }
  67077. }
  67078. if (childMesh) {
  67079. childMesh.setParent(parentMesh);
  67080. // Create our mesh info. Note that this method will always return non-null.
  67081. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67082. }
  67083. else {
  67084. BABYLON.Tools.Warn('Could not find root node in model file.');
  67085. }
  67086. return loadedMeshInfo;
  67087. };
  67088. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67089. var loadedMeshInfo = new LoadedMeshInfo();
  67090. var i;
  67091. loadedMeshInfo.rootNode = rootNode;
  67092. // Reset the caches
  67093. loadedMeshInfo.buttonMeshes = {};
  67094. loadedMeshInfo.axisMeshes = {};
  67095. // Button Meshes
  67096. for (i = 0; i < this._mapping.buttons.length; i++) {
  67097. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67098. if (!buttonMeshName) {
  67099. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67100. continue;
  67101. }
  67102. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67103. if (!buttonMesh) {
  67104. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67105. continue;
  67106. }
  67107. var buttonMeshInfo = {
  67108. index: i,
  67109. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67110. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67111. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67112. };
  67113. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67114. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67115. }
  67116. else {
  67117. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67118. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67119. '(VALUE: ' + !!buttonMeshInfo.value +
  67120. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67121. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67122. ')');
  67123. }
  67124. }
  67125. // Axis Meshes
  67126. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67127. var axisMeshName = this._mapping.axisMeshNames[i];
  67128. if (!axisMeshName) {
  67129. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67130. continue;
  67131. }
  67132. var axisMesh = getChildByName(rootNode, axisMeshName);
  67133. if (!axisMesh) {
  67134. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67135. continue;
  67136. }
  67137. var axisMeshInfo = {
  67138. index: i,
  67139. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67140. min: getImmediateChildByName(axisMesh, 'MIN'),
  67141. max: getImmediateChildByName(axisMesh, 'MAX')
  67142. };
  67143. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67144. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67145. }
  67146. else {
  67147. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67148. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67149. '(VALUE: ' + !!axisMeshInfo.value +
  67150. ', MIN: ' + !!axisMeshInfo.min +
  67151. ', MAX:' + !!axisMeshInfo.max +
  67152. ')');
  67153. }
  67154. }
  67155. // Pointing Ray
  67156. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67157. if (!loadedMeshInfo.pointingPoseNode) {
  67158. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67159. }
  67160. return loadedMeshInfo;
  67161. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67162. function getChildByName(node, name) {
  67163. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67164. }
  67165. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67166. function getImmediateChildByName(node, name) {
  67167. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67168. }
  67169. };
  67170. WindowsMotionController.prototype.getForwardRay = function (length) {
  67171. if (length === void 0) { length = 100; }
  67172. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67173. return _super.prototype.getForwardRay.call(this, length);
  67174. }
  67175. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67176. var origin = m.getTranslation();
  67177. var forward = new BABYLON.Vector3(0, 0, -1);
  67178. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67179. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67180. return new BABYLON.Ray(origin, direction, length);
  67181. };
  67182. WindowsMotionController.prototype.dispose = function () {
  67183. _super.prototype.dispose.call(this);
  67184. this.onTrackpadChangedObservable.clear();
  67185. };
  67186. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67187. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67188. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67189. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67190. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67191. return WindowsMotionController;
  67192. }(BABYLON.WebVRController));
  67193. BABYLON.WindowsMotionController = WindowsMotionController;
  67194. })(BABYLON || (BABYLON = {}));
  67195. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67196. "use strict";
  67197. var BABYLON;
  67198. (function (BABYLON) {
  67199. var GearVRController = /** @class */ (function (_super) {
  67200. __extends(GearVRController, _super);
  67201. function GearVRController(vrGamepad) {
  67202. var _this = _super.call(this, vrGamepad) || this;
  67203. _this._buttonIndexToObservableNameMap = [
  67204. 'onTrackpadChangedObservable',
  67205. 'onTriggerStateChangedObservable' // Trigger
  67206. ];
  67207. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67208. return _this;
  67209. }
  67210. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67211. var _this = this;
  67212. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67213. _this._defaultModel = newMeshes[1];
  67214. _this.attachToMesh(_this._defaultModel);
  67215. if (meshLoaded) {
  67216. meshLoaded(_this._defaultModel);
  67217. }
  67218. });
  67219. };
  67220. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67221. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67222. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67223. // Only emit events for buttons that we know how to map from index to observable
  67224. var observable = this[observableName];
  67225. if (observable) {
  67226. observable.notifyObservers(state);
  67227. }
  67228. }
  67229. };
  67230. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67231. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67232. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67233. return GearVRController;
  67234. }(BABYLON.WebVRController));
  67235. BABYLON.GearVRController = GearVRController;
  67236. })(BABYLON || (BABYLON = {}));
  67237. //# sourceMappingURL=babylon.gearVRController.js.map
  67238. "use strict";
  67239. var BABYLON;
  67240. (function (BABYLON) {
  67241. /**
  67242. * Google Daydream controller
  67243. */
  67244. var DaydreamController = /** @class */ (function (_super) {
  67245. __extends(DaydreamController, _super);
  67246. function DaydreamController(vrGamepad) {
  67247. var _this = _super.call(this, vrGamepad) || this;
  67248. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67249. return _this;
  67250. }
  67251. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67252. var _this = this;
  67253. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67254. _this._defaultModel = newMeshes[1];
  67255. _this.attachToMesh(_this._defaultModel);
  67256. if (meshLoaded) {
  67257. meshLoaded(_this._defaultModel);
  67258. }
  67259. });
  67260. };
  67261. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67262. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67263. if (buttonIdx === 0) {
  67264. var observable = this.onTriggerStateChangedObservable;
  67265. if (observable) {
  67266. observable.notifyObservers(state);
  67267. }
  67268. }
  67269. else {
  67270. // If the app or home buttons are ever made available
  67271. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67272. }
  67273. };
  67274. /**
  67275. * Base Url for the controller model.
  67276. */
  67277. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67278. /**
  67279. * File name for the controller model.
  67280. */
  67281. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67282. /**
  67283. * Gamepad Id prefix used to identify Daydream Controller.
  67284. */
  67285. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67286. return DaydreamController;
  67287. }(BABYLON.WebVRController));
  67288. BABYLON.DaydreamController = DaydreamController;
  67289. })(BABYLON || (BABYLON = {}));
  67290. //# sourceMappingURL=babylon.daydreamController.js.map
  67291. "use strict";
  67292. var BABYLON;
  67293. (function (BABYLON) {
  67294. var FollowCamera = /** @class */ (function (_super) {
  67295. __extends(FollowCamera, _super);
  67296. function FollowCamera(name, position, scene, lockedTarget) {
  67297. if (lockedTarget === void 0) { lockedTarget = null; }
  67298. var _this = _super.call(this, name, position, scene) || this;
  67299. _this.radius = 12;
  67300. _this.rotationOffset = 0;
  67301. _this.heightOffset = 4;
  67302. _this.cameraAcceleration = 0.05;
  67303. _this.maxCameraSpeed = 20;
  67304. _this.lockedTarget = lockedTarget;
  67305. return _this;
  67306. }
  67307. FollowCamera.prototype.getRadians = function (degrees) {
  67308. return degrees * Math.PI / 180;
  67309. };
  67310. FollowCamera.prototype.follow = function (cameraTarget) {
  67311. if (!cameraTarget)
  67312. return;
  67313. var yRotation;
  67314. if (cameraTarget.rotationQuaternion) {
  67315. var rotMatrix = new BABYLON.Matrix();
  67316. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67317. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67318. }
  67319. else {
  67320. yRotation = cameraTarget.rotation.y;
  67321. }
  67322. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67323. var targetPosition = cameraTarget.getAbsolutePosition();
  67324. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67325. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67326. var dx = targetX - this.position.x;
  67327. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67328. var dz = (targetZ) - this.position.z;
  67329. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67330. var vy = dy * this.cameraAcceleration;
  67331. var vz = dz * this.cameraAcceleration * 2;
  67332. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67333. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67334. }
  67335. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67336. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67337. }
  67338. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67339. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67340. }
  67341. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67342. this.setTarget(targetPosition);
  67343. };
  67344. FollowCamera.prototype._checkInputs = function () {
  67345. _super.prototype._checkInputs.call(this);
  67346. if (this.lockedTarget) {
  67347. this.follow(this.lockedTarget);
  67348. }
  67349. };
  67350. FollowCamera.prototype.getClassName = function () {
  67351. return "FollowCamera";
  67352. };
  67353. __decorate([
  67354. BABYLON.serialize()
  67355. ], FollowCamera.prototype, "radius", void 0);
  67356. __decorate([
  67357. BABYLON.serialize()
  67358. ], FollowCamera.prototype, "rotationOffset", void 0);
  67359. __decorate([
  67360. BABYLON.serialize()
  67361. ], FollowCamera.prototype, "heightOffset", void 0);
  67362. __decorate([
  67363. BABYLON.serialize()
  67364. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67365. __decorate([
  67366. BABYLON.serialize()
  67367. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67368. __decorate([
  67369. BABYLON.serializeAsMeshReference("lockedTargetId")
  67370. ], FollowCamera.prototype, "lockedTarget", void 0);
  67371. return FollowCamera;
  67372. }(BABYLON.TargetCamera));
  67373. BABYLON.FollowCamera = FollowCamera;
  67374. var ArcFollowCamera = /** @class */ (function (_super) {
  67375. __extends(ArcFollowCamera, _super);
  67376. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67377. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67378. _this.alpha = alpha;
  67379. _this.beta = beta;
  67380. _this.radius = radius;
  67381. _this.target = target;
  67382. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67383. _this.follow();
  67384. return _this;
  67385. }
  67386. ArcFollowCamera.prototype.follow = function () {
  67387. if (!this.target) {
  67388. return;
  67389. }
  67390. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67391. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67392. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67393. var targetPosition = this.target.getAbsolutePosition();
  67394. this.position = targetPosition.add(this._cartesianCoordinates);
  67395. this.setTarget(targetPosition);
  67396. };
  67397. ArcFollowCamera.prototype._checkInputs = function () {
  67398. _super.prototype._checkInputs.call(this);
  67399. this.follow();
  67400. };
  67401. ArcFollowCamera.prototype.getClassName = function () {
  67402. return "ArcFollowCamera";
  67403. };
  67404. return ArcFollowCamera;
  67405. }(BABYLON.TargetCamera));
  67406. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67407. })(BABYLON || (BABYLON = {}));
  67408. //# sourceMappingURL=babylon.followCamera.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 UniversalCamera = /** @class */ (function (_super) {
  67414. __extends(UniversalCamera, _super);
  67415. //-- end properties for backward compatibility for inputs
  67416. function UniversalCamera(name, position, scene) {
  67417. var _this = _super.call(this, name, position, scene) || this;
  67418. _this.inputs.addGamepad();
  67419. return _this;
  67420. }
  67421. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67422. //-- Begin properties for backward compatibility for inputs
  67423. get: function () {
  67424. var gamepad = this.inputs.attached["gamepad"];
  67425. if (gamepad)
  67426. return gamepad.gamepadAngularSensibility;
  67427. return 0;
  67428. },
  67429. set: function (value) {
  67430. var gamepad = this.inputs.attached["gamepad"];
  67431. if (gamepad)
  67432. gamepad.gamepadAngularSensibility = value;
  67433. },
  67434. enumerable: true,
  67435. configurable: true
  67436. });
  67437. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67438. get: function () {
  67439. var gamepad = this.inputs.attached["gamepad"];
  67440. if (gamepad)
  67441. return gamepad.gamepadMoveSensibility;
  67442. return 0;
  67443. },
  67444. set: function (value) {
  67445. var gamepad = this.inputs.attached["gamepad"];
  67446. if (gamepad)
  67447. gamepad.gamepadMoveSensibility = value;
  67448. },
  67449. enumerable: true,
  67450. configurable: true
  67451. });
  67452. UniversalCamera.prototype.getClassName = function () {
  67453. return "UniversalCamera";
  67454. };
  67455. return UniversalCamera;
  67456. }(BABYLON.TouchCamera));
  67457. BABYLON.UniversalCamera = UniversalCamera;
  67458. })(BABYLON || (BABYLON = {}));
  67459. //# sourceMappingURL=babylon.universalCamera.js.map
  67460. "use strict";
  67461. var BABYLON;
  67462. (function (BABYLON) {
  67463. // We're mainly based on the logic defined into the FreeCamera code
  67464. var GamepadCamera = /** @class */ (function (_super) {
  67465. __extends(GamepadCamera, _super);
  67466. //-- end properties for backward compatibility for inputs
  67467. function GamepadCamera(name, position, scene) {
  67468. return _super.call(this, name, position, scene) || this;
  67469. }
  67470. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67471. //-- Begin properties for backward compatibility for inputs
  67472. get: function () {
  67473. var gamepad = this.inputs.attached["gamepad"];
  67474. if (gamepad)
  67475. return gamepad.gamepadAngularSensibility;
  67476. return 0;
  67477. },
  67478. set: function (value) {
  67479. var gamepad = this.inputs.attached["gamepad"];
  67480. if (gamepad)
  67481. gamepad.gamepadAngularSensibility = value;
  67482. },
  67483. enumerable: true,
  67484. configurable: true
  67485. });
  67486. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67487. get: function () {
  67488. var gamepad = this.inputs.attached["gamepad"];
  67489. if (gamepad)
  67490. return gamepad.gamepadMoveSensibility;
  67491. return 0;
  67492. },
  67493. set: function (value) {
  67494. var gamepad = this.inputs.attached["gamepad"];
  67495. if (gamepad)
  67496. gamepad.gamepadMoveSensibility = value;
  67497. },
  67498. enumerable: true,
  67499. configurable: true
  67500. });
  67501. GamepadCamera.prototype.getClassName = function () {
  67502. return "GamepadCamera";
  67503. };
  67504. return GamepadCamera;
  67505. }(BABYLON.UniversalCamera));
  67506. BABYLON.GamepadCamera = GamepadCamera;
  67507. })(BABYLON || (BABYLON = {}));
  67508. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67509. "use strict";
  67510. var BABYLON;
  67511. (function (BABYLON) {
  67512. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67513. function PostProcessRenderPipelineManager() {
  67514. this._renderPipelines = {};
  67515. }
  67516. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67517. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67518. };
  67519. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67520. if (unique === void 0) { unique = false; }
  67521. var renderPipeline = this._renderPipelines[renderPipelineName];
  67522. if (!renderPipeline) {
  67523. return;
  67524. }
  67525. renderPipeline._attachCameras(cameras, unique);
  67526. };
  67527. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67528. var renderPipeline = this._renderPipelines[renderPipelineName];
  67529. if (!renderPipeline) {
  67530. return;
  67531. }
  67532. renderPipeline._detachCameras(cameras);
  67533. };
  67534. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67535. var renderPipeline = this._renderPipelines[renderPipelineName];
  67536. if (!renderPipeline) {
  67537. return;
  67538. }
  67539. renderPipeline._enableEffect(renderEffectName, cameras);
  67540. };
  67541. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67542. var renderPipeline = this._renderPipelines[renderPipelineName];
  67543. if (!renderPipeline) {
  67544. return;
  67545. }
  67546. renderPipeline._disableEffect(renderEffectName, cameras);
  67547. };
  67548. PostProcessRenderPipelineManager.prototype.update = function () {
  67549. for (var renderPipelineName in this._renderPipelines) {
  67550. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67551. var pipeline = this._renderPipelines[renderPipelineName];
  67552. if (!pipeline.isSupported) {
  67553. pipeline.dispose();
  67554. delete this._renderPipelines[renderPipelineName];
  67555. }
  67556. else {
  67557. pipeline._update();
  67558. }
  67559. }
  67560. }
  67561. };
  67562. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67563. for (var renderPipelineName in this._renderPipelines) {
  67564. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67565. var pipeline = this._renderPipelines[renderPipelineName];
  67566. pipeline._rebuild();
  67567. }
  67568. }
  67569. };
  67570. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67571. for (var renderPipelineName in this._renderPipelines) {
  67572. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67573. var pipeline = this._renderPipelines[renderPipelineName];
  67574. pipeline.dispose();
  67575. }
  67576. }
  67577. };
  67578. return PostProcessRenderPipelineManager;
  67579. }());
  67580. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67581. })(BABYLON || (BABYLON = {}));
  67582. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67583. "use strict";
  67584. var BABYLON;
  67585. (function (BABYLON) {
  67586. /**
  67587. * This represents a set of one or more post processes in Babylon.
  67588. * A post process can be used to apply a shader to a texture after it is rendered.
  67589. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67590. */
  67591. var PostProcessRenderEffect = /** @class */ (function () {
  67592. /**
  67593. * Instantiates a post process render effect.
  67594. * A post process can be used to apply a shader to a texture after it is rendered.
  67595. * @param engine The engine the effect is tied to
  67596. * @param name The name of the effect
  67597. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67598. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67599. */
  67600. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67601. this._name = name;
  67602. this._singleInstance = singleInstance || true;
  67603. this._getPostProcesses = getPostProcesses;
  67604. this._cameras = {};
  67605. this._indicesForCamera = {};
  67606. this._postProcesses = {};
  67607. }
  67608. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67609. /**
  67610. * Checks if all the post processes in the effect are supported.
  67611. */
  67612. get: function () {
  67613. for (var index in this._postProcesses) {
  67614. for (var ppIndex in this._postProcesses[index]) {
  67615. if (!this._postProcesses[index][ppIndex].isSupported) {
  67616. return false;
  67617. }
  67618. }
  67619. }
  67620. return true;
  67621. },
  67622. enumerable: true,
  67623. configurable: true
  67624. });
  67625. /**
  67626. * Updates the current state of the effect
  67627. */
  67628. PostProcessRenderEffect.prototype._update = function () {
  67629. };
  67630. /**
  67631. * Attaches the effect on cameras
  67632. * @param cameras The camera to attach to.
  67633. */
  67634. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67635. var _this = this;
  67636. var cameraKey;
  67637. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67638. if (!cams) {
  67639. return;
  67640. }
  67641. for (var i = 0; i < cams.length; i++) {
  67642. var camera = cams[i];
  67643. var cameraName = camera.name;
  67644. if (this._singleInstance) {
  67645. cameraKey = 0;
  67646. }
  67647. else {
  67648. cameraKey = cameraName;
  67649. }
  67650. if (!this._postProcesses[cameraKey]) {
  67651. var postProcess = this._getPostProcesses();
  67652. if (postProcess) {
  67653. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67654. }
  67655. }
  67656. if (!this._indicesForCamera[cameraName]) {
  67657. this._indicesForCamera[cameraName] = [];
  67658. }
  67659. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67660. var index = camera.attachPostProcess(postProcess);
  67661. _this._indicesForCamera[cameraName].push(index);
  67662. });
  67663. if (!this._cameras[cameraName]) {
  67664. this._cameras[cameraName] = camera;
  67665. }
  67666. }
  67667. };
  67668. /**
  67669. * Detatches the effect on cameras
  67670. * @param cameras The camera to detatch from.
  67671. */
  67672. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67673. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67674. if (!cams) {
  67675. return;
  67676. }
  67677. for (var i = 0; i < cams.length; i++) {
  67678. var camera = cams[i];
  67679. var cameraName = camera.name;
  67680. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67681. camera.detachPostProcess(postProcess);
  67682. });
  67683. if (this._cameras[cameraName]) {
  67684. //this._indicesForCamera.splice(index, 1);
  67685. this._cameras[cameraName] = null;
  67686. }
  67687. }
  67688. };
  67689. /**
  67690. * Enables the effect on given cameras
  67691. * @param cameras The camera to enable.
  67692. */
  67693. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67694. var _this = this;
  67695. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67696. if (!cams) {
  67697. return;
  67698. }
  67699. for (var i = 0; i < cams.length; i++) {
  67700. var camera = cams[i];
  67701. var cameraName = camera.name;
  67702. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67703. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67704. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67705. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67706. });
  67707. }
  67708. }
  67709. }
  67710. };
  67711. /**
  67712. * Disables the effect on the given cameras
  67713. * @param cameras The camera to disable.
  67714. */
  67715. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67716. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67717. if (!cams) {
  67718. return;
  67719. }
  67720. for (var i = 0; i < cams.length; i++) {
  67721. var camera = cams[i];
  67722. var cameraName = camera.name;
  67723. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67724. camera.detachPostProcess(postProcess);
  67725. });
  67726. }
  67727. };
  67728. /**
  67729. * Gets a list of the post processes contained in the effect.
  67730. * @param camera The camera to get the post processes on.
  67731. * @returns The list of the post processes in the effect.
  67732. */
  67733. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  67734. if (this._singleInstance) {
  67735. return this._postProcesses[0];
  67736. }
  67737. else {
  67738. if (!camera) {
  67739. return null;
  67740. }
  67741. return this._postProcesses[camera.name];
  67742. }
  67743. };
  67744. return PostProcessRenderEffect;
  67745. }());
  67746. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  67747. })(BABYLON || (BABYLON = {}));
  67748. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  67749. "use strict";
  67750. var BABYLON;
  67751. (function (BABYLON) {
  67752. var PostProcessRenderPipeline = /** @class */ (function () {
  67753. function PostProcessRenderPipeline(engine, name) {
  67754. this.engine = engine;
  67755. this._name = name;
  67756. this._renderEffects = {};
  67757. this._renderEffectsForIsolatedPass = new Array();
  67758. this._cameras = [];
  67759. }
  67760. PostProcessRenderPipeline.prototype.getClassName = function () {
  67761. return "PostProcessRenderPipeline";
  67762. };
  67763. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  67764. get: function () {
  67765. for (var renderEffectName in this._renderEffects) {
  67766. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67767. if (!this._renderEffects[renderEffectName].isSupported) {
  67768. return false;
  67769. }
  67770. }
  67771. }
  67772. return true;
  67773. },
  67774. enumerable: true,
  67775. configurable: true
  67776. });
  67777. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  67778. this._renderEffects[renderEffect._name] = renderEffect;
  67779. };
  67780. // private
  67781. PostProcessRenderPipeline.prototype._rebuild = function () {
  67782. };
  67783. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67784. var renderEffects = this._renderEffects[renderEffectName];
  67785. if (!renderEffects) {
  67786. return;
  67787. }
  67788. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67789. };
  67790. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67791. var renderEffects = this._renderEffects[renderEffectName];
  67792. if (!renderEffects) {
  67793. return;
  67794. }
  67795. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67796. };
  67797. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67798. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67799. if (!cams) {
  67800. return;
  67801. }
  67802. var indicesToDelete = [];
  67803. var i;
  67804. for (i = 0; i < cams.length; i++) {
  67805. var camera = cams[i];
  67806. var cameraName = camera.name;
  67807. if (this._cameras.indexOf(camera) === -1) {
  67808. this._cameras[cameraName] = camera;
  67809. }
  67810. else if (unique) {
  67811. indicesToDelete.push(i);
  67812. }
  67813. }
  67814. for (i = 0; i < indicesToDelete.length; i++) {
  67815. cameras.splice(indicesToDelete[i], 1);
  67816. }
  67817. for (var renderEffectName in this._renderEffects) {
  67818. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67819. this._renderEffects[renderEffectName]._attachCameras(cams);
  67820. }
  67821. }
  67822. };
  67823. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67824. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67825. if (!cams) {
  67826. return;
  67827. }
  67828. for (var renderEffectName in this._renderEffects) {
  67829. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67830. this._renderEffects[renderEffectName]._detachCameras(cams);
  67831. }
  67832. }
  67833. for (var i = 0; i < cams.length; i++) {
  67834. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  67835. }
  67836. };
  67837. PostProcessRenderPipeline.prototype._update = function () {
  67838. for (var renderEffectName in this._renderEffects) {
  67839. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67840. this._renderEffects[renderEffectName]._update();
  67841. }
  67842. }
  67843. for (var i = 0; i < this._cameras.length; i++) {
  67844. var cameraName = this._cameras[i].name;
  67845. if (this._renderEffectsForIsolatedPass[cameraName]) {
  67846. this._renderEffectsForIsolatedPass[cameraName]._update();
  67847. }
  67848. }
  67849. };
  67850. PostProcessRenderPipeline.prototype._reset = function () {
  67851. this._renderEffects = {};
  67852. this._renderEffectsForIsolatedPass = new Array();
  67853. };
  67854. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  67855. // 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)
  67856. var effectKeys = Object.keys(this._renderEffects);
  67857. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  67858. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  67859. if (postProcesses) {
  67860. postProcesses[0].samples = 4;
  67861. return true;
  67862. }
  67863. }
  67864. return false;
  67865. };
  67866. PostProcessRenderPipeline.prototype.dispose = function () {
  67867. // Must be implemented by children
  67868. };
  67869. __decorate([
  67870. BABYLON.serialize()
  67871. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  67872. return PostProcessRenderPipeline;
  67873. }());
  67874. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  67875. })(BABYLON || (BABYLON = {}));
  67876. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  67877. "use strict";
  67878. var BABYLON;
  67879. (function (BABYLON) {
  67880. /**
  67881. * This represents a depth renderer in Babylon.
  67882. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  67883. */
  67884. var DepthRenderer = /** @class */ (function () {
  67885. /**
  67886. * Instantiates a depth renderer
  67887. * @param scene The scene the renderer belongs to
  67888. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67889. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67890. */
  67891. function DepthRenderer(scene, type, camera) {
  67892. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67893. if (camera === void 0) { camera = null; }
  67894. var _this = this;
  67895. this._scene = scene;
  67896. this._camera = camera;
  67897. var engine = scene.getEngine();
  67898. // Render target
  67899. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67900. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67901. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67902. this._depthMap.refreshRate = 1;
  67903. this._depthMap.renderParticles = false;
  67904. this._depthMap.renderList = null;
  67905. // Camera to get depth map from to support multiple concurrent cameras
  67906. this._depthMap.activeCamera = this._camera;
  67907. this._depthMap.ignoreCameraViewport = true;
  67908. this._depthMap.useCameraPostProcesses = false;
  67909. // set default depth value to 1.0 (far away)
  67910. this._depthMap.onClearObservable.add(function (engine) {
  67911. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67912. });
  67913. // Custom render function
  67914. var renderSubMesh = function (subMesh) {
  67915. var mesh = subMesh.getRenderingMesh();
  67916. var scene = _this._scene;
  67917. var engine = scene.getEngine();
  67918. var material = subMesh.getMaterial();
  67919. if (!material) {
  67920. return;
  67921. }
  67922. // Culling and reverse (right handed system)
  67923. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67924. // Managing instances
  67925. var batch = mesh._getInstancesRenderList(subMesh._id);
  67926. if (batch.mustReturn) {
  67927. return;
  67928. }
  67929. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67930. var camera = _this._camera || scene.activeCamera;
  67931. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67932. engine.enableEffect(_this._effect);
  67933. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67934. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67935. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67936. // Alpha test
  67937. if (material && material.needAlphaTesting()) {
  67938. var alphaTexture = material.getAlphaTestTexture();
  67939. if (alphaTexture) {
  67940. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67941. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67942. }
  67943. }
  67944. // Bones
  67945. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67946. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67947. }
  67948. // Draw
  67949. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67950. }
  67951. };
  67952. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67953. var index;
  67954. if (depthOnlySubMeshes.length) {
  67955. engine.setColorWrite(false);
  67956. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67957. renderSubMesh(depthOnlySubMeshes.data[index]);
  67958. }
  67959. engine.setColorWrite(true);
  67960. }
  67961. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67962. renderSubMesh(opaqueSubMeshes.data[index]);
  67963. }
  67964. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67965. renderSubMesh(alphaTestSubMeshes.data[index]);
  67966. }
  67967. };
  67968. }
  67969. /**
  67970. * Creates the depth rendering effect and checks if the effect is ready.
  67971. * @param subMesh The submesh to be used to render the depth map of
  67972. * @param useInstances If multiple world instances should be used
  67973. * @returns if the depth renderer is ready to render the depth map
  67974. */
  67975. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67976. var material = subMesh.getMaterial();
  67977. if (material.disableDepthWrite) {
  67978. return false;
  67979. }
  67980. var defines = [];
  67981. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67982. var mesh = subMesh.getMesh();
  67983. // Alpha test
  67984. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67985. defines.push("#define ALPHATEST");
  67986. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67987. attribs.push(BABYLON.VertexBuffer.UVKind);
  67988. defines.push("#define UV1");
  67989. }
  67990. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67991. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67992. defines.push("#define UV2");
  67993. }
  67994. }
  67995. // Bones
  67996. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67997. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67998. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67999. if (mesh.numBoneInfluencers > 4) {
  68000. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68001. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68002. }
  68003. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68004. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68005. }
  68006. else {
  68007. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68008. }
  68009. // Instances
  68010. if (useInstances) {
  68011. defines.push("#define INSTANCES");
  68012. attribs.push("world0");
  68013. attribs.push("world1");
  68014. attribs.push("world2");
  68015. attribs.push("world3");
  68016. }
  68017. // Get correct effect
  68018. var join = defines.join("\n");
  68019. if (this._cachedDefines !== join) {
  68020. this._cachedDefines = join;
  68021. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  68022. }
  68023. return this._effect.isReady();
  68024. };
  68025. /**
  68026. * Gets the texture which the depth map will be written to.
  68027. * @returns The depth map texture
  68028. */
  68029. DepthRenderer.prototype.getDepthMap = function () {
  68030. return this._depthMap;
  68031. };
  68032. /**
  68033. * Disposes of the depth renderer.
  68034. */
  68035. DepthRenderer.prototype.dispose = function () {
  68036. this._depthMap.dispose();
  68037. };
  68038. return DepthRenderer;
  68039. }());
  68040. BABYLON.DepthRenderer = DepthRenderer;
  68041. })(BABYLON || (BABYLON = {}));
  68042. //# sourceMappingURL=babylon.depthRenderer.js.map
  68043. "use strict";
  68044. var BABYLON;
  68045. (function (BABYLON) {
  68046. var SSAORenderingPipeline = /** @class */ (function (_super) {
  68047. __extends(SSAORenderingPipeline, _super);
  68048. /**
  68049. * @constructor
  68050. * @param {string} name - The rendering pipeline name
  68051. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68052. * @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 }
  68053. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68054. */
  68055. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68056. var _this = _super.call(this, scene.getEngine(), name) || this;
  68057. // Members
  68058. /**
  68059. * The PassPostProcess id in the pipeline that contains the original scene color
  68060. * @type {string}
  68061. */
  68062. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68063. /**
  68064. * The SSAO PostProcess id in the pipeline
  68065. * @type {string}
  68066. */
  68067. _this.SSAORenderEffect = "SSAORenderEffect";
  68068. /**
  68069. * The horizontal blur PostProcess id in the pipeline
  68070. * @type {string}
  68071. */
  68072. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68073. /**
  68074. * The vertical blur PostProcess id in the pipeline
  68075. * @type {string}
  68076. */
  68077. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68078. /**
  68079. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68080. * @type {string}
  68081. */
  68082. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68083. /**
  68084. * The output strength of the SSAO post-process. Default value is 1.0.
  68085. * @type {number}
  68086. */
  68087. _this.totalStrength = 1.0;
  68088. /**
  68089. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68090. * @type {number}
  68091. */
  68092. _this.radius = 0.0001;
  68093. /**
  68094. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68095. * Must not be equal to fallOff and superior to fallOff.
  68096. * Default value is 0.975
  68097. * @type {number}
  68098. */
  68099. _this.area = 0.0075;
  68100. /**
  68101. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68102. * Must not be equal to area and inferior to area.
  68103. * Default value is 0.0
  68104. * @type {number}
  68105. */
  68106. _this.fallOff = 0.000001;
  68107. /**
  68108. * The base color of the SSAO post-process
  68109. * The final result is "base + ssao" between [0, 1]
  68110. * @type {number}
  68111. */
  68112. _this.base = 0.5;
  68113. _this._firstUpdate = true;
  68114. _this._scene = scene;
  68115. // Set up assets
  68116. _this._createRandomTexture();
  68117. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68118. var ssaoRatio = ratio.ssaoRatio || ratio;
  68119. var combineRatio = ratio.combineRatio || ratio;
  68120. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68121. _this._createSSAOPostProcess(ssaoRatio);
  68122. _this._createBlurPostProcess(ssaoRatio);
  68123. _this._createSSAOCombinePostProcess(combineRatio);
  68124. // Set up pipeline
  68125. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68127. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68128. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68129. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68130. // Finish
  68131. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68132. if (cameras)
  68133. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68134. return _this;
  68135. }
  68136. // Public Methods
  68137. /**
  68138. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68139. */
  68140. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68141. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68142. for (var i = 0; i < this._scene.cameras.length; i++) {
  68143. var camera = this._scene.cameras[i];
  68144. this._originalColorPostProcess.dispose(camera);
  68145. this._ssaoPostProcess.dispose(camera);
  68146. this._blurHPostProcess.dispose(camera);
  68147. this._blurVPostProcess.dispose(camera);
  68148. this._ssaoCombinePostProcess.dispose(camera);
  68149. }
  68150. this._randomTexture.dispose();
  68151. if (disableDepthRender)
  68152. this._scene.disableDepthRenderer();
  68153. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68154. _super.prototype.dispose.call(this);
  68155. };
  68156. // Private Methods
  68157. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68158. var _this = this;
  68159. var size = 16;
  68160. 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);
  68161. 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);
  68162. this._blurHPostProcess.onActivateObservable.add(function () {
  68163. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68164. _this._blurHPostProcess.kernel = size * dw;
  68165. });
  68166. this._blurVPostProcess.onActivateObservable.add(function () {
  68167. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68168. _this._blurVPostProcess.kernel = size * dw;
  68169. });
  68170. };
  68171. SSAORenderingPipeline.prototype._rebuild = function () {
  68172. this._firstUpdate = true;
  68173. _super.prototype._rebuild.call(this);
  68174. };
  68175. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68176. var _this = this;
  68177. var numSamples = 16;
  68178. var sampleSphere = [
  68179. 0.5381, 0.1856, -0.4319,
  68180. 0.1379, 0.2486, 0.4430,
  68181. 0.3371, 0.5679, -0.0057,
  68182. -0.6999, -0.0451, -0.0019,
  68183. 0.0689, -0.1598, -0.8547,
  68184. 0.0560, 0.0069, -0.1843,
  68185. -0.0146, 0.1402, 0.0762,
  68186. 0.0100, -0.1924, -0.0344,
  68187. -0.3577, -0.5301, -0.4358,
  68188. -0.3169, 0.1063, 0.0158,
  68189. 0.0103, -0.5869, 0.0046,
  68190. -0.0897, -0.4940, 0.3287,
  68191. 0.7119, -0.0154, -0.0918,
  68192. -0.0533, 0.0596, -0.5411,
  68193. 0.0352, -0.0631, 0.5460,
  68194. -0.4776, 0.2847, -0.0271
  68195. ];
  68196. var samplesFactor = 1.0 / numSamples;
  68197. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68198. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68199. "area", "fallOff", "base", "range", "viewport"
  68200. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68201. this._ssaoPostProcess.onApply = function (effect) {
  68202. if (_this._firstUpdate) {
  68203. effect.setArray3("sampleSphere", sampleSphere);
  68204. effect.setFloat("samplesFactor", samplesFactor);
  68205. effect.setFloat("randTextureTiles", 4.0);
  68206. }
  68207. effect.setFloat("totalStrength", _this.totalStrength);
  68208. effect.setFloat("radius", _this.radius);
  68209. effect.setFloat("area", _this.area);
  68210. effect.setFloat("fallOff", _this.fallOff);
  68211. effect.setFloat("base", _this.base);
  68212. effect.setTexture("textureSampler", _this._depthTexture);
  68213. effect.setTexture("randomSampler", _this._randomTexture);
  68214. };
  68215. };
  68216. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68217. var _this = this;
  68218. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68219. this._ssaoCombinePostProcess.onApply = function (effect) {
  68220. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68221. };
  68222. };
  68223. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68224. var size = 512;
  68225. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68226. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68227. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68228. var context = this._randomTexture.getContext();
  68229. var rand = function (min, max) {
  68230. return Math.random() * (max - min) + min;
  68231. };
  68232. var randVector = BABYLON.Vector3.Zero();
  68233. for (var x = 0; x < size; x++) {
  68234. for (var y = 0; y < size; y++) {
  68235. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68236. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68237. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68238. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68239. context.fillRect(x, y, 1, 1);
  68240. }
  68241. }
  68242. this._randomTexture.update(false);
  68243. };
  68244. __decorate([
  68245. BABYLON.serialize()
  68246. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68247. __decorate([
  68248. BABYLON.serialize()
  68249. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68250. __decorate([
  68251. BABYLON.serialize()
  68252. ], SSAORenderingPipeline.prototype, "area", void 0);
  68253. __decorate([
  68254. BABYLON.serialize()
  68255. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68256. __decorate([
  68257. BABYLON.serialize()
  68258. ], SSAORenderingPipeline.prototype, "base", void 0);
  68259. return SSAORenderingPipeline;
  68260. }(BABYLON.PostProcessRenderPipeline));
  68261. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68262. })(BABYLON || (BABYLON = {}));
  68263. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68264. "use strict";
  68265. var BABYLON;
  68266. (function (BABYLON) {
  68267. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68268. __extends(SSAO2RenderingPipeline, _super);
  68269. /**
  68270. * @constructor
  68271. * @param {string} name - The rendering pipeline name
  68272. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68273. * @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 }
  68274. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68275. */
  68276. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68277. var _this = _super.call(this, scene.getEngine(), name) || this;
  68278. // Members
  68279. /**
  68280. * The PassPostProcess id in the pipeline that contains the original scene color
  68281. * @type {string}
  68282. */
  68283. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68284. /**
  68285. * The SSAO PostProcess id in the pipeline
  68286. * @type {string}
  68287. */
  68288. _this.SSAORenderEffect = "SSAORenderEffect";
  68289. /**
  68290. * The horizontal blur PostProcess id in the pipeline
  68291. * @type {string}
  68292. */
  68293. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68294. /**
  68295. * The vertical blur PostProcess id in the pipeline
  68296. * @type {string}
  68297. */
  68298. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68299. /**
  68300. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68301. * @type {string}
  68302. */
  68303. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68304. /**
  68305. * The output strength of the SSAO post-process. Default value is 1.0.
  68306. * @type {number}
  68307. */
  68308. _this.totalStrength = 1.0;
  68309. /**
  68310. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68311. * @type {number}
  68312. */
  68313. _this.maxZ = 100.0;
  68314. /**
  68315. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68316. * @type {number}
  68317. */
  68318. _this.minZAspect = 0.2;
  68319. /**
  68320. * Number of samples used for the SSAO calculations. Default value is 8
  68321. * @type {number}
  68322. */
  68323. _this._samples = 8;
  68324. /**
  68325. * Are we using bilateral blur ?
  68326. * @type {boolean}
  68327. */
  68328. _this._expensiveBlur = true;
  68329. /**
  68330. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68331. * @type {number}
  68332. */
  68333. _this.radius = 2.0;
  68334. /**
  68335. * The base color of the SSAO post-process
  68336. * The final result is "base + ssao" between [0, 1]
  68337. * @type {number}
  68338. */
  68339. _this.base = 0.1;
  68340. _this._firstUpdate = true;
  68341. _this._scene = scene;
  68342. if (!_this.isSupported) {
  68343. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68344. return _this;
  68345. }
  68346. var ssaoRatio = ratio.ssaoRatio || ratio;
  68347. var blurRatio = ratio.blurRatio || ratio;
  68348. // Set up assets
  68349. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68350. _this._createRandomTexture();
  68351. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68352. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68353. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68354. _this._createSSAOPostProcess(1.0);
  68355. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68356. _this._createSSAOCombinePostProcess(blurRatio);
  68357. // Set up pipeline
  68358. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68359. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68360. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68361. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68362. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68363. // Finish
  68364. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68365. if (cameras)
  68366. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68367. return _this;
  68368. }
  68369. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68370. get: function () {
  68371. return this._samples;
  68372. },
  68373. set: function (n) {
  68374. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68375. this._samples = n;
  68376. this._sampleSphere = this._generateHemisphere();
  68377. this._firstUpdate = true;
  68378. },
  68379. enumerable: true,
  68380. configurable: true
  68381. });
  68382. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68383. get: function () {
  68384. return this._expensiveBlur;
  68385. },
  68386. set: function (b) {
  68387. 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"]);
  68388. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68389. this._expensiveBlur = b;
  68390. this._firstUpdate = true;
  68391. },
  68392. enumerable: true,
  68393. configurable: true
  68394. });
  68395. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68396. /**
  68397. * Support test.
  68398. * @type {boolean}
  68399. */
  68400. get: function () {
  68401. var engine = BABYLON.Engine.LastCreatedEngine;
  68402. if (!engine) {
  68403. return false;
  68404. }
  68405. return engine.getCaps().drawBuffersExtension;
  68406. },
  68407. enumerable: true,
  68408. configurable: true
  68409. });
  68410. // Public Methods
  68411. /**
  68412. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68413. */
  68414. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68415. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68416. for (var i = 0; i < this._scene.cameras.length; i++) {
  68417. var camera = this._scene.cameras[i];
  68418. this._originalColorPostProcess.dispose(camera);
  68419. this._ssaoPostProcess.dispose(camera);
  68420. this._blurHPostProcess.dispose(camera);
  68421. this._blurVPostProcess.dispose(camera);
  68422. this._ssaoCombinePostProcess.dispose(camera);
  68423. }
  68424. this._randomTexture.dispose();
  68425. if (disableGeometryBufferRenderer)
  68426. this._scene.disableGeometryBufferRenderer();
  68427. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68428. _super.prototype.dispose.call(this);
  68429. };
  68430. // Private Methods
  68431. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68432. var _this = this;
  68433. this._samplerOffsets = [];
  68434. var expensive = this.expensiveBlur;
  68435. for (var i = -8; i < 8; i++) {
  68436. this._samplerOffsets.push(i * 2 + 0.5);
  68437. }
  68438. 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");
  68439. this._blurHPostProcess.onApply = function (effect) {
  68440. if (!_this._scene.activeCamera) {
  68441. return;
  68442. }
  68443. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68444. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68445. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68446. effect.setFloat("radius", _this.radius);
  68447. effect.setTexture("depthSampler", _this._depthTexture);
  68448. if (_this._firstUpdate) {
  68449. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68450. }
  68451. };
  68452. 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");
  68453. this._blurVPostProcess.onApply = function (effect) {
  68454. if (!_this._scene.activeCamera) {
  68455. return;
  68456. }
  68457. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68458. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68459. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68460. effect.setFloat("radius", _this.radius);
  68461. effect.setTexture("depthSampler", _this._depthTexture);
  68462. if (_this._firstUpdate) {
  68463. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68464. _this._firstUpdate = false;
  68465. }
  68466. };
  68467. };
  68468. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68469. this._firstUpdate = true;
  68470. _super.prototype._rebuild.call(this);
  68471. };
  68472. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68473. var numSamples = this.samples;
  68474. var result = [];
  68475. var vector, scale;
  68476. var rand = function (min, max) {
  68477. return Math.random() * (max - min) + min;
  68478. };
  68479. var i = 0;
  68480. while (i < numSamples) {
  68481. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68482. vector.normalize();
  68483. scale = i / numSamples;
  68484. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68485. vector.scaleInPlace(scale);
  68486. result.push(vector.x, vector.y, vector.z);
  68487. i++;
  68488. }
  68489. return result;
  68490. };
  68491. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68492. var _this = this;
  68493. var numSamples = this.samples;
  68494. this._sampleSphere = this._generateHemisphere();
  68495. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68496. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68497. "base", "range", "projection", "near", "far", "texelSize",
  68498. "xViewport", "yViewport", "maxZ", "minZAspect"
  68499. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68500. this._ssaoPostProcess.onApply = function (effect) {
  68501. if (_this._firstUpdate) {
  68502. effect.setArray3("sampleSphere", _this._sampleSphere);
  68503. effect.setFloat("randTextureTiles", 4.0);
  68504. }
  68505. if (!_this._scene.activeCamera) {
  68506. return;
  68507. }
  68508. effect.setFloat("samplesFactor", 1 / _this.samples);
  68509. effect.setFloat("totalStrength", _this.totalStrength);
  68510. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68511. effect.setFloat("radius", _this.radius);
  68512. effect.setFloat("maxZ", _this.maxZ);
  68513. effect.setFloat("minZAspect", _this.minZAspect);
  68514. effect.setFloat("base", _this.base);
  68515. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68516. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68517. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68518. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68519. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68520. effect.setTexture("textureSampler", _this._depthTexture);
  68521. effect.setTexture("normalSampler", _this._normalTexture);
  68522. effect.setTexture("randomSampler", _this._randomTexture);
  68523. };
  68524. };
  68525. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68526. var _this = this;
  68527. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68528. this._ssaoCombinePostProcess.onApply = function (effect) {
  68529. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68530. };
  68531. };
  68532. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68533. var size = 512;
  68534. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68535. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68536. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68537. var context = this._randomTexture.getContext();
  68538. var rand = function (min, max) {
  68539. return Math.random() * (max - min) + min;
  68540. };
  68541. var randVector = BABYLON.Vector3.Zero();
  68542. for (var x = 0; x < size; x++) {
  68543. for (var y = 0; y < size; y++) {
  68544. randVector.x = rand(0.0, 1.0);
  68545. randVector.y = rand(0.0, 1.0);
  68546. randVector.z = 0.0;
  68547. randVector.normalize();
  68548. randVector.scaleInPlace(255);
  68549. randVector.x = Math.floor(randVector.x);
  68550. randVector.y = Math.floor(randVector.y);
  68551. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68552. context.fillRect(x, y, 1, 1);
  68553. }
  68554. }
  68555. this._randomTexture.update(false);
  68556. };
  68557. __decorate([
  68558. BABYLON.serialize()
  68559. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68560. __decorate([
  68561. BABYLON.serialize()
  68562. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68563. __decorate([
  68564. BABYLON.serialize()
  68565. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68566. __decorate([
  68567. BABYLON.serialize("samples")
  68568. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68569. __decorate([
  68570. BABYLON.serialize("expensiveBlur")
  68571. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68572. __decorate([
  68573. BABYLON.serialize()
  68574. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68575. __decorate([
  68576. BABYLON.serialize()
  68577. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68578. return SSAO2RenderingPipeline;
  68579. }(BABYLON.PostProcessRenderPipeline));
  68580. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68581. })(BABYLON || (BABYLON = {}));
  68582. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68583. "use strict";
  68584. // BABYLON.JS Chromatic Aberration GLSL Shader
  68585. // Author: Olivier Guyot
  68586. // Separates very slightly R, G and B colors on the edges of the screen
  68587. // Inspired by Francois Tarlier & Martins Upitis
  68588. var BABYLON;
  68589. (function (BABYLON) {
  68590. var LensRenderingPipeline = /** @class */ (function (_super) {
  68591. __extends(LensRenderingPipeline, _super);
  68592. /**
  68593. * @constructor
  68594. *
  68595. * Effect parameters are as follow:
  68596. * {
  68597. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68598. * edge_blur: number; // from 0 to x (1 for realism)
  68599. * distortion: number; // from 0 to x (1 for realism)
  68600. * grain_amount: number; // from 0 to 1
  68601. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68602. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68603. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68604. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68605. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68606. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68607. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68608. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68609. * }
  68610. * Note: if an effect parameter is unset, effect is disabled
  68611. *
  68612. * @param {string} name - The rendering pipeline name
  68613. * @param {object} parameters - An object containing all parameters (see above)
  68614. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68615. * @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)
  68616. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68617. */
  68618. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68619. if (ratio === void 0) { ratio = 1.0; }
  68620. var _this = _super.call(this, scene.getEngine(), name) || this;
  68621. // Lens effects can be of the following:
  68622. // - chromatic aberration (slight shift of RGB colors)
  68623. // - blur on the edge of the lens
  68624. // - lens distortion
  68625. // - depth-of-field blur & highlights enhancing
  68626. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68627. // - grain effect (noise or custom texture)
  68628. // Two additional texture samplers are needed:
  68629. // - depth map (for depth-of-field)
  68630. // - grain texture
  68631. /**
  68632. * The chromatic aberration PostProcess id in the pipeline
  68633. * @type {string}
  68634. */
  68635. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68636. /**
  68637. * The highlights enhancing PostProcess id in the pipeline
  68638. * @type {string}
  68639. */
  68640. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68641. /**
  68642. * The depth-of-field PostProcess id in the pipeline
  68643. * @type {string}
  68644. */
  68645. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68646. _this._scene = scene;
  68647. // Fetch texture samplers
  68648. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68649. if (parameters.grain_texture) {
  68650. _this._grainTexture = parameters.grain_texture;
  68651. }
  68652. else {
  68653. _this._createGrainTexture();
  68654. }
  68655. // save parameters
  68656. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68657. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68658. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68659. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68660. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68661. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68662. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68663. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68664. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68665. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68666. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68667. // Create effects
  68668. _this._createChromaticAberrationPostProcess(ratio);
  68669. _this._createHighlightsPostProcess(ratio);
  68670. _this._createDepthOfFieldPostProcess(ratio / 4);
  68671. // Set up pipeline
  68672. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68673. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68674. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68675. if (_this._highlightsGain === -1) {
  68676. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68677. }
  68678. // Finish
  68679. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68680. if (cameras) {
  68681. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68682. }
  68683. return _this;
  68684. }
  68685. // public methods (self explanatory)
  68686. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68687. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68688. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68689. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68690. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68691. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68692. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68693. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68694. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68695. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68696. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68697. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68698. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68699. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68700. };
  68701. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68702. this._highlightsPostProcess.updateEffect();
  68703. };
  68704. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68705. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68706. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68707. this._highlightsGain = amount;
  68708. };
  68709. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68710. if (this._highlightsGain === -1) {
  68711. this._highlightsGain = 1.0;
  68712. }
  68713. this._highlightsThreshold = amount;
  68714. };
  68715. LensRenderingPipeline.prototype.disableHighlights = function () {
  68716. this._highlightsGain = -1;
  68717. };
  68718. /**
  68719. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68720. */
  68721. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68722. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68723. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68724. this._chromaticAberrationPostProcess = null;
  68725. this._highlightsPostProcess = null;
  68726. this._depthOfFieldPostProcess = null;
  68727. this._grainTexture.dispose();
  68728. if (disableDepthRender)
  68729. this._scene.disableDepthRenderer();
  68730. };
  68731. // colors shifting and distortion
  68732. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68733. var _this = this;
  68734. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68735. [], // samplers
  68736. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68737. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68738. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68739. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68740. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68741. effect.setFloat('radialIntensity', 1);
  68742. effect.setFloat2('direction', 17, 17);
  68743. effect.setFloat2('centerPosition', 0.5, 0.5);
  68744. };
  68745. };
  68746. // highlights enhancing
  68747. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68748. var _this = this;
  68749. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68750. [], // samplers
  68751. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68752. this._highlightsPostProcess.onApply = function (effect) {
  68753. effect.setFloat('gain', _this._highlightsGain);
  68754. effect.setFloat('threshold', _this._highlightsThreshold);
  68755. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  68756. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68757. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68758. };
  68759. };
  68760. // colors shifting and distortion
  68761. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  68762. var _this = this;
  68763. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  68764. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  68765. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  68766. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68767. this._depthOfFieldPostProcess.onApply = function (effect) {
  68768. effect.setTexture("depthSampler", _this._depthTexture);
  68769. effect.setTexture("grainSampler", _this._grainTexture);
  68770. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  68771. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  68772. effect.setFloat('grain_amount', _this._grainAmount);
  68773. effect.setBool('blur_noise', _this._blurNoise);
  68774. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68775. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68776. effect.setFloat('distortion', _this._distortion);
  68777. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  68778. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  68779. effect.setFloat('aperture', _this._dofAperture);
  68780. effect.setFloat('darken', _this._dofDarken);
  68781. effect.setFloat('edge_blur', _this._edgeBlur);
  68782. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68783. if (_this._scene.activeCamera) {
  68784. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68785. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68786. }
  68787. };
  68788. };
  68789. // creates a black and white random noise texture, 512x512
  68790. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68791. var size = 512;
  68792. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68793. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68794. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68795. var context = this._grainTexture.getContext();
  68796. var rand = function (min, max) {
  68797. return Math.random() * (max - min) + min;
  68798. };
  68799. var value;
  68800. for (var x = 0; x < size; x++) {
  68801. for (var y = 0; y < size; y++) {
  68802. value = Math.floor(rand(0.42, 0.58) * 255);
  68803. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68804. context.fillRect(x, y, 1, 1);
  68805. }
  68806. }
  68807. this._grainTexture.update(false);
  68808. };
  68809. return LensRenderingPipeline;
  68810. }(BABYLON.PostProcessRenderPipeline));
  68811. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68812. })(BABYLON || (BABYLON = {}));
  68813. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68814. "use strict";
  68815. var BABYLON;
  68816. (function (BABYLON) {
  68817. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68818. __extends(StandardRenderingPipeline, _super);
  68819. /**
  68820. * @constructor
  68821. * @param {string} name - The rendering pipeline name
  68822. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68823. * @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)
  68824. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68825. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68826. */
  68827. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68828. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68829. var _this = _super.call(this, scene.getEngine(), name) || this;
  68830. _this.downSampleX4PostProcess = null;
  68831. _this.brightPassPostProcess = null;
  68832. _this.blurHPostProcesses = [];
  68833. _this.blurVPostProcesses = [];
  68834. _this.textureAdderPostProcess = null;
  68835. _this.volumetricLightPostProcess = null;
  68836. _this.volumetricLightSmoothXPostProcess = null;
  68837. _this.volumetricLightSmoothYPostProcess = null;
  68838. _this.volumetricLightMergePostProces = null;
  68839. _this.volumetricLightFinalPostProcess = null;
  68840. _this.luminancePostProcess = null;
  68841. _this.luminanceDownSamplePostProcesses = [];
  68842. _this.hdrPostProcess = null;
  68843. _this.textureAdderFinalPostProcess = null;
  68844. _this.lensFlareFinalPostProcess = null;
  68845. _this.hdrFinalPostProcess = null;
  68846. _this.lensFlarePostProcess = null;
  68847. _this.lensFlareComposePostProcess = null;
  68848. _this.motionBlurPostProcess = null;
  68849. _this.depthOfFieldPostProcess = null;
  68850. // Values
  68851. _this.brightThreshold = 1.0;
  68852. _this.blurWidth = 512.0;
  68853. _this.horizontalBlur = false;
  68854. _this.exposure = 1.0;
  68855. _this.lensTexture = null;
  68856. _this.volumetricLightCoefficient = 0.2;
  68857. _this.volumetricLightPower = 4.0;
  68858. _this.volumetricLightBlurScale = 64.0;
  68859. _this.sourceLight = null;
  68860. _this.hdrMinimumLuminance = 1.0;
  68861. _this.hdrDecreaseRate = 0.5;
  68862. _this.hdrIncreaseRate = 0.5;
  68863. _this.lensColorTexture = null;
  68864. _this.lensFlareStrength = 20.0;
  68865. _this.lensFlareGhostDispersal = 1.4;
  68866. _this.lensFlareHaloWidth = 0.7;
  68867. _this.lensFlareDistortionStrength = 16.0;
  68868. _this.lensStarTexture = null;
  68869. _this.lensFlareDirtTexture = null;
  68870. _this.depthOfFieldDistance = 10.0;
  68871. _this.depthOfFieldBlurWidth = 64.0;
  68872. _this.motionStrength = 1.0;
  68873. // IAnimatable
  68874. _this.animations = [];
  68875. _this._currentDepthOfFieldSource = null;
  68876. _this._hdrCurrentLuminance = 1.0;
  68877. // Getters and setters
  68878. _this._bloomEnabled = true;
  68879. _this._depthOfFieldEnabled = false;
  68880. _this._vlsEnabled = false;
  68881. _this._lensFlareEnabled = false;
  68882. _this._hdrEnabled = false;
  68883. _this._motionBlurEnabled = false;
  68884. _this._motionBlurSamples = 64.0;
  68885. _this._volumetricLightStepsCount = 50.0;
  68886. _this._cameras = cameras || [];
  68887. // Initialize
  68888. _this._scene = scene;
  68889. _this._basePostProcess = originalPostProcess;
  68890. _this._ratio = ratio;
  68891. // Misc
  68892. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68893. // Finish
  68894. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68895. _this._buildPipeline();
  68896. return _this;
  68897. }
  68898. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68899. get: function () {
  68900. return this._bloomEnabled;
  68901. },
  68902. set: function (enabled) {
  68903. if (this._bloomEnabled === enabled) {
  68904. return;
  68905. }
  68906. this._bloomEnabled = enabled;
  68907. this._buildPipeline();
  68908. },
  68909. enumerable: true,
  68910. configurable: true
  68911. });
  68912. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68913. get: function () {
  68914. return this._depthOfFieldEnabled;
  68915. },
  68916. set: function (enabled) {
  68917. if (this._depthOfFieldEnabled === enabled) {
  68918. return;
  68919. }
  68920. this._depthOfFieldEnabled = enabled;
  68921. this._buildPipeline();
  68922. },
  68923. enumerable: true,
  68924. configurable: true
  68925. });
  68926. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68927. get: function () {
  68928. return this._lensFlareEnabled;
  68929. },
  68930. set: function (enabled) {
  68931. if (this._lensFlareEnabled === enabled) {
  68932. return;
  68933. }
  68934. this._lensFlareEnabled = enabled;
  68935. this._buildPipeline();
  68936. },
  68937. enumerable: true,
  68938. configurable: true
  68939. });
  68940. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68941. get: function () {
  68942. return this._hdrEnabled;
  68943. },
  68944. set: function (enabled) {
  68945. if (this._hdrEnabled === enabled) {
  68946. return;
  68947. }
  68948. this._hdrEnabled = enabled;
  68949. this._buildPipeline();
  68950. },
  68951. enumerable: true,
  68952. configurable: true
  68953. });
  68954. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68955. get: function () {
  68956. return this._vlsEnabled;
  68957. },
  68958. set: function (enabled) {
  68959. if (this._vlsEnabled === enabled) {
  68960. return;
  68961. }
  68962. if (enabled) {
  68963. var geometry = this._scene.enableGeometryBufferRenderer();
  68964. if (!geometry) {
  68965. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68966. return;
  68967. }
  68968. }
  68969. this._vlsEnabled = enabled;
  68970. this._buildPipeline();
  68971. },
  68972. enumerable: true,
  68973. configurable: true
  68974. });
  68975. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68976. get: function () {
  68977. return this._motionBlurEnabled;
  68978. },
  68979. set: function (enabled) {
  68980. if (this._motionBlurEnabled === enabled) {
  68981. return;
  68982. }
  68983. this._motionBlurEnabled = enabled;
  68984. this._buildPipeline();
  68985. },
  68986. enumerable: true,
  68987. configurable: true
  68988. });
  68989. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68990. get: function () {
  68991. return this._volumetricLightStepsCount;
  68992. },
  68993. set: function (count) {
  68994. if (this.volumetricLightPostProcess) {
  68995. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68996. }
  68997. this._volumetricLightStepsCount = count;
  68998. },
  68999. enumerable: true,
  69000. configurable: true
  69001. });
  69002. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  69003. get: function () {
  69004. return this._motionBlurSamples;
  69005. },
  69006. set: function (samples) {
  69007. if (this.motionBlurPostProcess) {
  69008. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  69009. }
  69010. this._motionBlurSamples = samples;
  69011. },
  69012. enumerable: true,
  69013. configurable: true
  69014. });
  69015. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69016. var _this = this;
  69017. var ratio = this._ratio;
  69018. var scene = this._scene;
  69019. this._disposePostProcesses();
  69020. this._reset();
  69021. // Create pass post-process
  69022. if (!this._basePostProcess) {
  69023. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  69024. this.originalPostProcess.onApply = function (effect) {
  69025. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  69026. };
  69027. }
  69028. else {
  69029. this.originalPostProcess = this._basePostProcess;
  69030. }
  69031. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  69032. this._currentDepthOfFieldSource = this.originalPostProcess;
  69033. if (this._vlsEnabled) {
  69034. // Create volumetric light
  69035. this._createVolumetricLightPostProcess(scene, ratio);
  69036. // Create volumetric light final post-process
  69037. 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);
  69038. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  69039. }
  69040. if (this._bloomEnabled) {
  69041. // Create down sample X4 post-process
  69042. this._createDownSampleX4PostProcess(scene, ratio / 2);
  69043. // Create bright pass post-process
  69044. this._createBrightPassPostProcess(scene, ratio / 2);
  69045. // Create gaussian blur post-processes (down sampling blurs)
  69046. this._createBlurPostProcesses(scene, ratio / 4, 1);
  69047. // Create texture adder post-process
  69048. this._createTextureAdderPostProcess(scene, ratio);
  69049. // Create depth-of-field source post-process
  69050. 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);
  69051. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69052. }
  69053. if (this._lensFlareEnabled) {
  69054. // Create lens flare post-process
  69055. this._createLensFlarePostProcess(scene, ratio);
  69056. // Create depth-of-field source post-process post lens-flare and disable it now
  69057. 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);
  69058. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69059. }
  69060. if (this._hdrEnabled) {
  69061. // Create luminance
  69062. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69063. // Create HDR
  69064. this._createHdrPostProcess(scene, ratio);
  69065. // Create depth-of-field source post-process post hdr and disable it now
  69066. 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);
  69067. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69068. }
  69069. if (this._depthOfFieldEnabled) {
  69070. // Create gaussian blur used by depth-of-field
  69071. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69072. // Create depth-of-field post-process
  69073. this._createDepthOfFieldPostProcess(scene, ratio);
  69074. }
  69075. if (this._motionBlurEnabled) {
  69076. // Create motion blur post-process
  69077. this._createMotionBlurPostProcess(scene, ratio);
  69078. }
  69079. if (this._cameras !== null) {
  69080. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69081. }
  69082. };
  69083. // Down Sample X4 Post-Processs
  69084. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69085. var _this = this;
  69086. var downSampleX4Offsets = new Array(32);
  69087. 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);
  69088. this.downSampleX4PostProcess.onApply = function (effect) {
  69089. var id = 0;
  69090. var width = _this.downSampleX4PostProcess.width;
  69091. var height = _this.downSampleX4PostProcess.height;
  69092. for (var i = -2; i < 2; i++) {
  69093. for (var j = -2; j < 2; j++) {
  69094. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69095. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69096. id += 2;
  69097. }
  69098. }
  69099. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69100. };
  69101. // Add to pipeline
  69102. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69103. };
  69104. // Brightpass Post-Process
  69105. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69106. var _this = this;
  69107. var brightOffsets = new Array(8);
  69108. 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);
  69109. this.brightPassPostProcess.onApply = function (effect) {
  69110. var sU = (1.0 / _this.brightPassPostProcess.width);
  69111. var sV = (1.0 / _this.brightPassPostProcess.height);
  69112. brightOffsets[0] = -0.5 * sU;
  69113. brightOffsets[1] = 0.5 * sV;
  69114. brightOffsets[2] = 0.5 * sU;
  69115. brightOffsets[3] = 0.5 * sV;
  69116. brightOffsets[4] = -0.5 * sU;
  69117. brightOffsets[5] = -0.5 * sV;
  69118. brightOffsets[6] = 0.5 * sU;
  69119. brightOffsets[7] = -0.5 * sV;
  69120. effect.setArray2("dsOffsets", brightOffsets);
  69121. effect.setFloat("brightThreshold", _this.brightThreshold);
  69122. };
  69123. // Add to pipeline
  69124. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69125. };
  69126. // Create blur H&V post-processes
  69127. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69128. var _this = this;
  69129. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69130. var engine = scene.getEngine();
  69131. 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);
  69132. 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);
  69133. blurX.onActivateObservable.add(function () {
  69134. var dw = blurX.width / engine.getRenderWidth();
  69135. blurX.kernel = _this[blurWidthKey] * dw;
  69136. });
  69137. blurY.onActivateObservable.add(function () {
  69138. var dw = blurY.height / engine.getRenderHeight();
  69139. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69140. });
  69141. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69142. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69143. this.blurHPostProcesses.push(blurX);
  69144. this.blurVPostProcesses.push(blurY);
  69145. };
  69146. // Create texture adder post-process
  69147. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69148. var _this = this;
  69149. 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);
  69150. this.textureAdderPostProcess.onApply = function (effect) {
  69151. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69152. effect.setTexture("lensSampler", _this.lensTexture);
  69153. effect.setFloat("exposure", _this.exposure);
  69154. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69155. };
  69156. // Add to pipeline
  69157. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69158. };
  69159. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69160. var _this = this;
  69161. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69162. geometryRenderer.enablePosition = true;
  69163. var geometry = geometryRenderer.getGBuffer();
  69164. // Base post-process
  69165. 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));
  69166. var depthValues = BABYLON.Vector2.Zero();
  69167. this.volumetricLightPostProcess.onApply = function (effect) {
  69168. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69169. var generator = _this.sourceLight.getShadowGenerator();
  69170. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69171. effect.setTexture("positionSampler", geometry.textures[2]);
  69172. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69173. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69174. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69175. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69176. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69177. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69178. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69179. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69180. effect.setVector2("depthValues", depthValues);
  69181. }
  69182. };
  69183. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69184. // Smooth
  69185. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69186. // Merge
  69187. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69188. this.volumetricLightMergePostProces.onApply = function (effect) {
  69189. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69190. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69191. };
  69192. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69193. };
  69194. // Create luminance
  69195. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69196. var _this = this;
  69197. // Create luminance
  69198. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69199. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69200. var offsets = [];
  69201. this.luminancePostProcess.onApply = function (effect) {
  69202. var sU = (1.0 / _this.luminancePostProcess.width);
  69203. var sV = (1.0 / _this.luminancePostProcess.height);
  69204. offsets[0] = -0.5 * sU;
  69205. offsets[1] = 0.5 * sV;
  69206. offsets[2] = 0.5 * sU;
  69207. offsets[3] = 0.5 * sV;
  69208. offsets[4] = -0.5 * sU;
  69209. offsets[5] = -0.5 * sV;
  69210. offsets[6] = 0.5 * sU;
  69211. offsets[7] = -0.5 * sV;
  69212. effect.setArray2("lumOffsets", offsets);
  69213. };
  69214. // Add to pipeline
  69215. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69216. // Create down sample luminance
  69217. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69218. var size = Math.pow(3, i);
  69219. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69220. if (i === 0) {
  69221. defines += "#define FINAL_DOWN_SAMPLER";
  69222. }
  69223. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69224. this.luminanceDownSamplePostProcesses.push(postProcess);
  69225. }
  69226. // Create callbacks and add effects
  69227. var lastLuminance = this.luminancePostProcess;
  69228. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69229. var downSampleOffsets = new Array(18);
  69230. pp.onApply = function (effect) {
  69231. if (!lastLuminance) {
  69232. return;
  69233. }
  69234. var id = 0;
  69235. for (var x = -1; x < 2; x++) {
  69236. for (var y = -1; y < 2; y++) {
  69237. downSampleOffsets[id] = x / lastLuminance.width;
  69238. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69239. id += 2;
  69240. }
  69241. }
  69242. effect.setArray2("dsOffsets", downSampleOffsets);
  69243. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69244. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69245. lastLuminance = _this.luminancePostProcess;
  69246. }
  69247. else {
  69248. lastLuminance = pp;
  69249. }
  69250. };
  69251. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69252. pp.onAfterRender = function (effect) {
  69253. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69254. 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);
  69255. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69256. };
  69257. }
  69258. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69259. });
  69260. };
  69261. // Create HDR post-process
  69262. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69263. var _this = this;
  69264. 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);
  69265. var outputLiminance = 1;
  69266. var time = 0;
  69267. var lastTime = 0;
  69268. this.hdrPostProcess.onApply = function (effect) {
  69269. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69270. time += scene.getEngine().getDeltaTime();
  69271. if (outputLiminance < 0) {
  69272. outputLiminance = _this._hdrCurrentLuminance;
  69273. }
  69274. else {
  69275. var dt = (lastTime - time) / 1000.0;
  69276. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69277. outputLiminance += _this.hdrDecreaseRate * dt;
  69278. }
  69279. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69280. outputLiminance -= _this.hdrIncreaseRate * dt;
  69281. }
  69282. else {
  69283. outputLiminance = _this._hdrCurrentLuminance;
  69284. }
  69285. }
  69286. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69287. effect.setFloat("averageLuminance", outputLiminance);
  69288. lastTime = time;
  69289. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69290. };
  69291. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69292. };
  69293. // Create lens flare post-process
  69294. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69295. var _this = this;
  69296. 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);
  69297. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69298. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69299. 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);
  69300. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69301. var resolution = new BABYLON.Vector2(0, 0);
  69302. // Lens flare
  69303. this.lensFlarePostProcess.onApply = function (effect) {
  69304. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69305. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69306. effect.setFloat("strength", _this.lensFlareStrength);
  69307. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69308. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69309. // Shift
  69310. resolution.x = _this.lensFlarePostProcess.width;
  69311. resolution.y = _this.lensFlarePostProcess.height;
  69312. effect.setVector2("resolution", resolution);
  69313. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69314. };
  69315. // Compose
  69316. 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);
  69317. 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);
  69318. this.lensFlareComposePostProcess.onApply = function (effect) {
  69319. if (!_this._scene.activeCamera) {
  69320. return;
  69321. }
  69322. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69323. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69324. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69325. // Lens start rotation matrix
  69326. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69327. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69328. 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));
  69329. camRot *= 4.0;
  69330. 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);
  69331. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69332. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69333. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69334. };
  69335. };
  69336. // Create depth-of-field post-process
  69337. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69338. var _this = this;
  69339. 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);
  69340. this.depthOfFieldPostProcess.onApply = function (effect) {
  69341. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69342. effect.setTexture("depthSampler", _this._getDepthTexture());
  69343. effect.setFloat("distance", _this.depthOfFieldDistance);
  69344. };
  69345. // Add to pipeline
  69346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69347. };
  69348. // Create motion blur post-process
  69349. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69350. var _this = this;
  69351. 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);
  69352. var motionScale = 0;
  69353. var prevViewProjection = BABYLON.Matrix.Identity();
  69354. var invViewProjection = BABYLON.Matrix.Identity();
  69355. var viewProjection = BABYLON.Matrix.Identity();
  69356. var screenSize = BABYLON.Vector2.Zero();
  69357. this.motionBlurPostProcess.onApply = function (effect) {
  69358. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69359. viewProjection.invertToRef(invViewProjection);
  69360. effect.setMatrix("inverseViewProjection", invViewProjection);
  69361. effect.setMatrix("prevViewProjection", prevViewProjection);
  69362. prevViewProjection = viewProjection;
  69363. screenSize.x = _this.motionBlurPostProcess.width;
  69364. screenSize.y = _this.motionBlurPostProcess.height;
  69365. effect.setVector2("screenSize", screenSize);
  69366. motionScale = scene.getEngine().getFps() / 60.0;
  69367. effect.setFloat("motionScale", motionScale);
  69368. effect.setFloat("motionStrength", _this.motionStrength);
  69369. effect.setTexture("depthSampler", _this._getDepthTexture());
  69370. };
  69371. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69372. };
  69373. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69374. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69375. var renderer = this._scene.enableGeometryBufferRenderer();
  69376. return renderer.getGBuffer().textures[0];
  69377. }
  69378. return this._scene.enableDepthRenderer().getDepthMap();
  69379. };
  69380. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69381. for (var i = 0; i < this._cameras.length; i++) {
  69382. var camera = this._cameras[i];
  69383. if (this.originalPostProcess) {
  69384. this.originalPostProcess.dispose(camera);
  69385. }
  69386. if (this.downSampleX4PostProcess) {
  69387. this.downSampleX4PostProcess.dispose(camera);
  69388. }
  69389. if (this.brightPassPostProcess) {
  69390. this.brightPassPostProcess.dispose(camera);
  69391. }
  69392. if (this.textureAdderPostProcess) {
  69393. this.textureAdderPostProcess.dispose(camera);
  69394. }
  69395. if (this.textureAdderFinalPostProcess) {
  69396. this.textureAdderFinalPostProcess.dispose(camera);
  69397. }
  69398. if (this.volumetricLightPostProcess) {
  69399. this.volumetricLightPostProcess.dispose(camera);
  69400. }
  69401. if (this.volumetricLightSmoothXPostProcess) {
  69402. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69403. }
  69404. if (this.volumetricLightSmoothYPostProcess) {
  69405. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69406. }
  69407. if (this.volumetricLightMergePostProces) {
  69408. this.volumetricLightMergePostProces.dispose(camera);
  69409. }
  69410. if (this.volumetricLightFinalPostProcess) {
  69411. this.volumetricLightFinalPostProcess.dispose(camera);
  69412. }
  69413. if (this.lensFlarePostProcess) {
  69414. this.lensFlarePostProcess.dispose(camera);
  69415. }
  69416. if (this.lensFlareComposePostProcess) {
  69417. this.lensFlareComposePostProcess.dispose(camera);
  69418. }
  69419. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69420. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69421. }
  69422. if (this.luminancePostProcess) {
  69423. this.luminancePostProcess.dispose(camera);
  69424. }
  69425. if (this.hdrPostProcess) {
  69426. this.hdrPostProcess.dispose(camera);
  69427. }
  69428. if (this.hdrFinalPostProcess) {
  69429. this.hdrFinalPostProcess.dispose(camera);
  69430. }
  69431. if (this.depthOfFieldPostProcess) {
  69432. this.depthOfFieldPostProcess.dispose(camera);
  69433. }
  69434. if (this.motionBlurPostProcess) {
  69435. this.motionBlurPostProcess.dispose(camera);
  69436. }
  69437. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69438. this.blurHPostProcesses[j].dispose(camera);
  69439. }
  69440. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69441. this.blurVPostProcesses[j].dispose(camera);
  69442. }
  69443. }
  69444. this.originalPostProcess = null;
  69445. this.downSampleX4PostProcess = null;
  69446. this.brightPassPostProcess = null;
  69447. this.textureAdderPostProcess = null;
  69448. this.textureAdderFinalPostProcess = null;
  69449. this.volumetricLightPostProcess = null;
  69450. this.volumetricLightSmoothXPostProcess = null;
  69451. this.volumetricLightSmoothYPostProcess = null;
  69452. this.volumetricLightMergePostProces = null;
  69453. this.volumetricLightFinalPostProcess = null;
  69454. this.lensFlarePostProcess = null;
  69455. this.lensFlareComposePostProcess = null;
  69456. this.luminancePostProcess = null;
  69457. this.hdrPostProcess = null;
  69458. this.hdrFinalPostProcess = null;
  69459. this.depthOfFieldPostProcess = null;
  69460. this.motionBlurPostProcess = null;
  69461. this.luminanceDownSamplePostProcesses = [];
  69462. this.blurHPostProcesses = [];
  69463. this.blurVPostProcesses = [];
  69464. };
  69465. // Dispose
  69466. StandardRenderingPipeline.prototype.dispose = function () {
  69467. this._disposePostProcesses();
  69468. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69469. _super.prototype.dispose.call(this);
  69470. };
  69471. // Serialize rendering pipeline
  69472. StandardRenderingPipeline.prototype.serialize = function () {
  69473. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69474. serializationObject.customType = "StandardRenderingPipeline";
  69475. return serializationObject;
  69476. };
  69477. /**
  69478. * Static members
  69479. */
  69480. // Parse serialized pipeline
  69481. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69482. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69483. };
  69484. // Luminance steps
  69485. StandardRenderingPipeline.LuminanceSteps = 6;
  69486. __decorate([
  69487. BABYLON.serialize()
  69488. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69489. __decorate([
  69490. BABYLON.serialize()
  69491. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69492. __decorate([
  69493. BABYLON.serialize()
  69494. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69495. __decorate([
  69496. BABYLON.serialize()
  69497. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69498. __decorate([
  69499. BABYLON.serializeAsTexture("lensTexture")
  69500. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69501. __decorate([
  69502. BABYLON.serialize()
  69503. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69504. __decorate([
  69505. BABYLON.serialize()
  69506. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69507. __decorate([
  69508. BABYLON.serialize()
  69509. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69510. __decorate([
  69511. BABYLON.serialize()
  69512. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69513. __decorate([
  69514. BABYLON.serialize()
  69515. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69516. __decorate([
  69517. BABYLON.serialize()
  69518. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69519. __decorate([
  69520. BABYLON.serializeAsTexture("lensColorTexture")
  69521. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69522. __decorate([
  69523. BABYLON.serialize()
  69524. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69525. __decorate([
  69526. BABYLON.serialize()
  69527. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69528. __decorate([
  69529. BABYLON.serialize()
  69530. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69531. __decorate([
  69532. BABYLON.serialize()
  69533. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69534. __decorate([
  69535. BABYLON.serializeAsTexture("lensStarTexture")
  69536. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69537. __decorate([
  69538. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69539. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69540. __decorate([
  69541. BABYLON.serialize()
  69542. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69543. __decorate([
  69544. BABYLON.serialize()
  69545. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69546. __decorate([
  69547. BABYLON.serialize()
  69548. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69549. __decorate([
  69550. BABYLON.serialize()
  69551. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69552. __decorate([
  69553. BABYLON.serialize()
  69554. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69555. __decorate([
  69556. BABYLON.serialize()
  69557. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69558. __decorate([
  69559. BABYLON.serialize()
  69560. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69561. __decorate([
  69562. BABYLON.serialize()
  69563. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69564. __decorate([
  69565. BABYLON.serialize()
  69566. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69567. __decorate([
  69568. BABYLON.serialize()
  69569. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69570. __decorate([
  69571. BABYLON.serialize()
  69572. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69573. __decorate([
  69574. BABYLON.serialize()
  69575. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69576. return StandardRenderingPipeline;
  69577. }(BABYLON.PostProcessRenderPipeline));
  69578. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69579. })(BABYLON || (BABYLON = {}));
  69580. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69581. "use strict";
  69582. var BABYLON;
  69583. (function (BABYLON) {
  69584. var FxaaPostProcess = /** @class */ (function (_super) {
  69585. __extends(FxaaPostProcess, _super);
  69586. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69587. if (camera === void 0) { camera = null; }
  69588. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69589. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69590. _this.onApplyObservable.add(function (effect) {
  69591. var texelSize = _this.texelSize;
  69592. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69593. });
  69594. return _this;
  69595. }
  69596. return FxaaPostProcess;
  69597. }(BABYLON.PostProcess));
  69598. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69599. })(BABYLON || (BABYLON = {}));
  69600. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69601. "use strict";
  69602. var BABYLON;
  69603. (function (BABYLON) {
  69604. /**
  69605. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69606. */
  69607. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69608. __extends(ChromaticAberrationPostProcess, _super);
  69609. /**
  69610. * Creates a new instance of @see ChromaticAberrationPostProcess
  69611. * @param name The name of the effect.
  69612. * @param screenWidth The width of the screen to apply the effect on.
  69613. * @param screenHeight The height of the screen to apply the effect on.
  69614. * @param options The required width/height ratio to downsize to before computing the render pass.
  69615. * @param camera The camera to apply the render pass to.
  69616. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69617. * @param engine The engine which the post process will be applied. (default: current engine)
  69618. * @param reusable If the post process can be reused on the same frame. (default: false)
  69619. * @param textureType Type of textures used when performing the post process. (default: 0)
  69620. * @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)
  69621. */
  69622. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69623. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69624. if (blockCompilation === void 0) { blockCompilation = false; }
  69625. 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;
  69626. /**
  69627. * The amount of seperation of rgb channels (default: 30)
  69628. */
  69629. _this.aberrationAmount = 30;
  69630. /**
  69631. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69632. */
  69633. _this.radialIntensity = 0;
  69634. /**
  69635. * 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))
  69636. */
  69637. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69638. /**
  69639. * 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))
  69640. */
  69641. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69642. _this.onApplyObservable.add(function (effect) {
  69643. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69644. effect.setFloat('screen_width', screenWidth);
  69645. effect.setFloat('screen_height', screenHeight);
  69646. effect.setFloat('radialIntensity', _this.radialIntensity);
  69647. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69648. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69649. });
  69650. return _this;
  69651. }
  69652. return ChromaticAberrationPostProcess;
  69653. }(BABYLON.PostProcess));
  69654. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69655. })(BABYLON || (BABYLON = {}));
  69656. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69657. "use strict";
  69658. var BABYLON;
  69659. (function (BABYLON) {
  69660. /**
  69661. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69662. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69663. */
  69664. var SharpenPostProcess = /** @class */ (function (_super) {
  69665. __extends(SharpenPostProcess, _super);
  69666. /**
  69667. * Creates a new instance of @see ConvolutionPostProcess
  69668. * @param name The name of the effect.
  69669. * @param options The required width/height ratio to downsize to before computing the render pass.
  69670. * @param camera The camera to apply the render pass to.
  69671. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69672. * @param engine The engine which the post process will be applied. (default: current engine)
  69673. * @param reusable If the post process can be reused on the same frame. (default: false)
  69674. * @param textureType Type of textures used when performing the post process. (default: 0)
  69675. * @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)
  69676. */
  69677. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69678. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69679. if (blockCompilation === void 0) { blockCompilation = false; }
  69680. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69681. /**
  69682. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69683. */
  69684. _this.colorAmount = 1.0;
  69685. /**
  69686. * How much sharpness should be applied (default: 0.3)
  69687. */
  69688. _this.edgeAmount = 0.3;
  69689. _this.onApply = function (effect) {
  69690. effect.setFloat2("screenSize", _this.width, _this.height);
  69691. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69692. };
  69693. return _this;
  69694. }
  69695. return SharpenPostProcess;
  69696. }(BABYLON.PostProcess));
  69697. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69698. })(BABYLON || (BABYLON = {}));
  69699. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69700. "use strict";
  69701. var BABYLON;
  69702. (function (BABYLON) {
  69703. /**
  69704. * The Blur Post Process which blurs an image based on a kernel and direction.
  69705. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69706. */
  69707. var BlurPostProcess = /** @class */ (function (_super) {
  69708. __extends(BlurPostProcess, _super);
  69709. /**
  69710. * Creates a new instance of @see BlurPostProcess
  69711. * @param name The name of the effect.
  69712. * @param direction The direction in which to blur the image.
  69713. * @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.
  69714. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69715. * @param camera The camera to apply the render pass to.
  69716. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69717. * @param engine The engine which the post process will be applied. (default: current engine)
  69718. * @param reusable If the post process can be reused on the same frame. (default: false)
  69719. * @param textureType Type of textures used when performing the post process. (default: 0)
  69720. * @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)
  69721. */
  69722. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  69723. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69724. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69725. if (defines === void 0) { defines = ""; }
  69726. if (blockCompilation === void 0) { blockCompilation = false; }
  69727. 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;
  69728. _this.direction = direction;
  69729. _this.blockCompilation = blockCompilation;
  69730. _this._packedFloat = false;
  69731. _this._staticDefines = "";
  69732. _this._staticDefines = defines;
  69733. _this.onApplyObservable.add(function (effect) {
  69734. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69735. });
  69736. _this.kernel = kernel;
  69737. return _this;
  69738. }
  69739. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69740. /**
  69741. * Gets the length in pixels of the blur sample region
  69742. */
  69743. get: function () {
  69744. return this._idealKernel;
  69745. },
  69746. /**
  69747. * Sets the length in pixels of the blur sample region
  69748. */
  69749. set: function (v) {
  69750. if (this._idealKernel === v) {
  69751. return;
  69752. }
  69753. v = Math.max(v, 1);
  69754. this._idealKernel = v;
  69755. this._kernel = this._nearestBestKernel(v);
  69756. if (!this.blockCompilation) {
  69757. this._updateParameters();
  69758. }
  69759. },
  69760. enumerable: true,
  69761. configurable: true
  69762. });
  69763. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69764. /**
  69765. * Gets wether or not the blur is unpacking/repacking floats
  69766. */
  69767. get: function () {
  69768. return this._packedFloat;
  69769. },
  69770. /**
  69771. * Sets wether or not the blur needs to unpack/repack floats
  69772. */
  69773. set: function (v) {
  69774. if (this._packedFloat === v) {
  69775. return;
  69776. }
  69777. this._packedFloat = v;
  69778. if (!this.blockCompilation) {
  69779. this._updateParameters();
  69780. }
  69781. },
  69782. enumerable: true,
  69783. configurable: true
  69784. });
  69785. /**
  69786. * Updates the effect with the current post process compile time values and recompiles the shader.
  69787. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69788. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69789. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69790. * @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
  69791. * @param onCompiled Called when the shader has been compiled.
  69792. * @param onError Called if there is an error when compiling a shader.
  69793. */
  69794. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69795. if (defines === void 0) { defines = null; }
  69796. if (uniforms === void 0) { uniforms = null; }
  69797. if (samplers === void 0) { samplers = null; }
  69798. this._updateParameters(onCompiled, onError);
  69799. };
  69800. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69801. // Generate sampling offsets and weights
  69802. var N = this._kernel;
  69803. var centerIndex = (N - 1) / 2;
  69804. // Generate Gaussian sampling weights over kernel
  69805. var offsets = [];
  69806. var weights = [];
  69807. var totalWeight = 0;
  69808. for (var i = 0; i < N; i++) {
  69809. var u = i / (N - 1);
  69810. var w = this._gaussianWeight(u * 2.0 - 1);
  69811. offsets[i] = (i - centerIndex);
  69812. weights[i] = w;
  69813. totalWeight += w;
  69814. }
  69815. // Normalize weights
  69816. for (var i = 0; i < weights.length; i++) {
  69817. weights[i] /= totalWeight;
  69818. }
  69819. // Optimize: combine samples to take advantage of hardware linear sampling
  69820. // Walk from left to center, combining pairs (symmetrically)
  69821. var linearSamplingWeights = [];
  69822. var linearSamplingOffsets = [];
  69823. var linearSamplingMap = [];
  69824. for (var i = 0; i <= centerIndex; i += 2) {
  69825. var j = Math.min(i + 1, Math.floor(centerIndex));
  69826. var singleCenterSample = i === j;
  69827. if (singleCenterSample) {
  69828. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69829. }
  69830. else {
  69831. var sharedCell = j === centerIndex;
  69832. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69833. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69834. if (offsetLinear === 0) {
  69835. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69836. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69837. }
  69838. else {
  69839. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69840. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69841. }
  69842. }
  69843. }
  69844. for (var i = 0; i < linearSamplingMap.length; i++) {
  69845. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69846. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69847. }
  69848. // Replace with optimized
  69849. offsets = linearSamplingOffsets;
  69850. weights = linearSamplingWeights;
  69851. // Generate shaders
  69852. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69853. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69854. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69855. var defines = "";
  69856. defines += this._staticDefines;
  69857. for (var i = 0; i < varyingCount; i++) {
  69858. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69859. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69860. }
  69861. var depCount = 0;
  69862. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69863. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69864. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69865. depCount++;
  69866. }
  69867. if (this.packedFloat) {
  69868. defines += "#define PACKEDFLOAT 1";
  69869. }
  69870. _super.prototype.updateEffect.call(this, defines, null, null, {
  69871. varyingCount: varyingCount,
  69872. depCount: depCount
  69873. }, onCompiled, onError);
  69874. };
  69875. /**
  69876. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69877. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69878. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69879. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69880. * The gaps between physical kernels are compensated for in the weighting of the samples
  69881. * @param idealKernel Ideal blur kernel.
  69882. * @return Nearest best kernel.
  69883. */
  69884. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69885. var v = Math.round(idealKernel);
  69886. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69887. var k = _a[_i];
  69888. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69889. return Math.max(k, 3);
  69890. }
  69891. }
  69892. return Math.max(v, 3);
  69893. };
  69894. /**
  69895. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69896. * @param x The point on the Gaussian distribution to sample.
  69897. * @return the value of the Gaussian function at x.
  69898. */
  69899. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69900. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69901. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69902. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69903. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69904. // truncated at around 1.3% of peak strength.
  69905. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69906. var sigma = (1 / 3);
  69907. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69908. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69909. var weight = (1.0 / denominator) * Math.exp(exponent);
  69910. return weight;
  69911. };
  69912. /**
  69913. * Generates a string that can be used as a floating point number in GLSL.
  69914. * @param x Value to print.
  69915. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69916. * @return GLSL float string.
  69917. */
  69918. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69919. if (decimalFigures === void 0) { decimalFigures = 8; }
  69920. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69921. };
  69922. return BlurPostProcess;
  69923. }(BABYLON.PostProcess));
  69924. BABYLON.BlurPostProcess = BlurPostProcess;
  69925. })(BABYLON || (BABYLON = {}));
  69926. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69927. "use strict";
  69928. var BABYLON;
  69929. (function (BABYLON) {
  69930. /**
  69931. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69932. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69933. * based on samples that have a large difference in distance than the center pixel.
  69934. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69935. */
  69936. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69937. __extends(DepthOfFieldBlurPostProcess, _super);
  69938. /**
  69939. * Creates a new instance of @see CircleOfConfusionPostProcess
  69940. * @param name The name of the effect.
  69941. * @param scene The scene the effect belongs to.
  69942. * @param direction The direction the blur should be applied.
  69943. * @param kernel The size of the kernel used to blur.
  69944. * @param options The required width/height ratio to downsize to before computing the render pass.
  69945. * @param camera The camera to apply the render pass to.
  69946. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69947. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69948. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69949. * @param engine The engine which the post process will be applied. (default: current engine)
  69950. * @param reusable If the post process can be reused on the same frame. (default: false)
  69951. * @param textureType Type of textures used when performing the post process. (default: 0)
  69952. * @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)
  69953. */
  69954. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69955. if (imageToBlur === void 0) { imageToBlur = null; }
  69956. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69957. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69958. if (blockCompilation === void 0) { blockCompilation = false; }
  69959. 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;
  69960. _this.direction = direction;
  69961. _this.onApplyObservable.add(function (effect) {
  69962. if (imageToBlur != null) {
  69963. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69964. }
  69965. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69966. if (scene.activeCamera) {
  69967. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69968. }
  69969. });
  69970. return _this;
  69971. }
  69972. return DepthOfFieldBlurPostProcess;
  69973. }(BABYLON.BlurPostProcess));
  69974. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69975. })(BABYLON || (BABYLON = {}));
  69976. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69977. "use strict";
  69978. var BABYLON;
  69979. (function (BABYLON) {
  69980. /**
  69981. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69982. */
  69983. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69984. __extends(DepthOfFieldMergePostProcess, _super);
  69985. /**
  69986. * Creates a new instance of @see CircleOfConfusionPostProcess
  69987. * @param name The name of the effect.
  69988. * @param original The non-blurred image to be modified
  69989. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69990. * @param blurSteps Incrimental bluring post processes.
  69991. * @param options The required width/height ratio to downsize to before computing the render pass.
  69992. * @param camera The camera to apply the render pass to.
  69993. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69994. * @param engine The engine which the post process will be applied. (default: current engine)
  69995. * @param reusable If the post process can be reused on the same frame. (default: false)
  69996. * @param textureType Type of textures used when performing the post process. (default: 0)
  69997. * @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)
  69998. */
  69999. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70000. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70001. if (blockCompilation === void 0) { blockCompilation = false; }
  70002. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70003. _this.blurSteps = blurSteps;
  70004. _this.onApplyObservable.add(function (effect) {
  70005. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70006. effect.setTextureFromPostProcess("textureSampler", original);
  70007. blurSteps.forEach(function (step, index) {
  70008. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  70009. });
  70010. });
  70011. if (!blockCompilation) {
  70012. _this.updateEffect();
  70013. }
  70014. return _this;
  70015. }
  70016. /**
  70017. * Updates the effect with the current post process compile time values and recompiles the shader.
  70018. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70019. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70020. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70021. * @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
  70022. * @param onCompiled Called when the shader has been compiled.
  70023. * @param onError Called if there is an error when compiling a shader.
  70024. */
  70025. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70026. if (defines === void 0) { defines = null; }
  70027. if (uniforms === void 0) { uniforms = null; }
  70028. if (samplers === void 0) { samplers = null; }
  70029. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  70030. };
  70031. return DepthOfFieldMergePostProcess;
  70032. }(BABYLON.PostProcess));
  70033. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  70034. })(BABYLON || (BABYLON = {}));
  70035. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  70036. "use strict";
  70037. var BABYLON;
  70038. (function (BABYLON) {
  70039. /**
  70040. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  70041. */
  70042. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  70043. __extends(CircleOfConfusionPostProcess, _super);
  70044. /**
  70045. * Creates a new instance of @see CircleOfConfusionPostProcess
  70046. * @param name The name of the effect.
  70047. * @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.
  70048. * @param options The required width/height ratio to downsize to before computing the render pass.
  70049. * @param camera The camera to apply the render pass to.
  70050. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70051. * @param engine The engine which the post process will be applied. (default: current engine)
  70052. * @param reusable If the post process can be reused on the same frame. (default: false)
  70053. * @param textureType Type of textures used when performing the post process. (default: 0)
  70054. * @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)
  70055. */
  70056. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70057. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70058. if (blockCompilation === void 0) { blockCompilation = false; }
  70059. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70060. /**
  70061. * 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.
  70062. */
  70063. _this.lensSize = 50;
  70064. /**
  70065. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70066. */
  70067. _this.fStop = 1.4;
  70068. /**
  70069. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70070. */
  70071. _this.focusDistance = 2000;
  70072. /**
  70073. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70074. */
  70075. _this.focalLength = 50;
  70076. _this._depthTexture = null;
  70077. _this._depthTexture = depthTexture;
  70078. _this.onApplyObservable.add(function (effect) {
  70079. if (!_this._depthTexture) {
  70080. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70081. return;
  70082. }
  70083. effect.setTexture("depthSampler", _this._depthTexture);
  70084. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70085. var aperture = _this.lensSize / _this.fStop;
  70086. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70087. effect.setFloat('focusDistance', _this.focusDistance);
  70088. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70089. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70090. });
  70091. return _this;
  70092. }
  70093. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70094. /**
  70095. * 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.
  70096. */
  70097. set: function (value) {
  70098. this._depthTexture = value;
  70099. },
  70100. enumerable: true,
  70101. configurable: true
  70102. });
  70103. return CircleOfConfusionPostProcess;
  70104. }(BABYLON.PostProcess));
  70105. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70106. })(BABYLON || (BABYLON = {}));
  70107. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70108. "use strict";
  70109. var BABYLON;
  70110. (function (BABYLON) {
  70111. /**
  70112. * Specifies the level of max blur that should be applied when using the depth of field effect
  70113. */
  70114. var DepthOfFieldEffectBlurLevel;
  70115. (function (DepthOfFieldEffectBlurLevel) {
  70116. /**
  70117. * Subtle blur
  70118. */
  70119. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70120. /**
  70121. * Medium blur
  70122. */
  70123. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70124. /**
  70125. * Large blur
  70126. */
  70127. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70128. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70129. ;
  70130. /**
  70131. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70132. */
  70133. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70134. __extends(DepthOfFieldEffect, _super);
  70135. /**
  70136. * Creates a new instance of @see DepthOfFieldEffect
  70137. * @param scene The scene the effect belongs to.
  70138. * @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.
  70139. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70140. * @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)
  70141. */
  70142. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70143. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70144. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70145. if (blockCompilation === void 0) { blockCompilation = false; }
  70146. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70147. return _this._effects;
  70148. }, true) || this;
  70149. _this._effects = [];
  70150. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70151. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70152. // 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)
  70153. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70154. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70155. _this._depthOfFieldBlurY = [];
  70156. _this._depthOfFieldBlurX = [];
  70157. var blurCount = 1;
  70158. var kernelSize = 15;
  70159. switch (blurLevel) {
  70160. case DepthOfFieldEffectBlurLevel.High: {
  70161. blurCount = 3;
  70162. kernelSize = 51;
  70163. break;
  70164. }
  70165. case DepthOfFieldEffectBlurLevel.Medium: {
  70166. blurCount = 2;
  70167. kernelSize = 31;
  70168. break;
  70169. }
  70170. default: {
  70171. kernelSize = 15;
  70172. blurCount = 1;
  70173. break;
  70174. }
  70175. }
  70176. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70177. for (var i = 0; i < blurCount; i++) {
  70178. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70179. blurY.autoClear = false;
  70180. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70181. blurX.autoClear = false;
  70182. _this._depthOfFieldBlurY.push(blurY);
  70183. _this._depthOfFieldBlurX.push(blurX);
  70184. }
  70185. // Merge blurred images with original image based on circleOfConfusion
  70186. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70187. _this._depthOfFieldMerge.autoClear = false;
  70188. // Set all post processes on the effect.
  70189. _this._effects = [_this._circleOfConfusion];
  70190. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70191. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70192. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70193. }
  70194. _this._effects.push(_this._depthOfFieldMerge);
  70195. return _this;
  70196. }
  70197. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70198. get: function () {
  70199. return this._circleOfConfusion.focalLength;
  70200. },
  70201. /**
  70202. * The focal the length of the camera used in the effect
  70203. */
  70204. set: function (value) {
  70205. this._circleOfConfusion.focalLength = value;
  70206. },
  70207. enumerable: true,
  70208. configurable: true
  70209. });
  70210. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70211. get: function () {
  70212. return this._circleOfConfusion.fStop;
  70213. },
  70214. /**
  70215. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70216. */
  70217. set: function (value) {
  70218. this._circleOfConfusion.fStop = value;
  70219. },
  70220. enumerable: true,
  70221. configurable: true
  70222. });
  70223. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70224. get: function () {
  70225. return this._circleOfConfusion.focusDistance;
  70226. },
  70227. /**
  70228. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70229. */
  70230. set: function (value) {
  70231. this._circleOfConfusion.focusDistance = value;
  70232. },
  70233. enumerable: true,
  70234. configurable: true
  70235. });
  70236. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70237. get: function () {
  70238. return this._circleOfConfusion.lensSize;
  70239. },
  70240. /**
  70241. * 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.
  70242. */
  70243. set: function (value) {
  70244. this._circleOfConfusion.lensSize = value;
  70245. },
  70246. enumerable: true,
  70247. configurable: true
  70248. });
  70249. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70250. /**
  70251. * 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.
  70252. */
  70253. set: function (value) {
  70254. this._circleOfConfusion.depthTexture = value;
  70255. },
  70256. enumerable: true,
  70257. configurable: true
  70258. });
  70259. /**
  70260. * Disposes each of the internal effects for a given camera.
  70261. * @param camera The camera to dispose the effect on.
  70262. */
  70263. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70264. this._circleOfConfusion.dispose(camera);
  70265. this._depthOfFieldBlurX.forEach(function (element) {
  70266. element.dispose(camera);
  70267. });
  70268. this._depthOfFieldBlurY.forEach(function (element) {
  70269. element.dispose(camera);
  70270. });
  70271. this._depthOfFieldMerge.dispose(camera);
  70272. };
  70273. /**
  70274. * Internal
  70275. */
  70276. DepthOfFieldEffect.prototype._updateEffects = function () {
  70277. for (var effect in this._effects) {
  70278. this._effects[effect].updateEffect();
  70279. }
  70280. };
  70281. /**
  70282. * Internal
  70283. * @returns if all the contained post processes are ready.
  70284. */
  70285. DepthOfFieldEffect.prototype._isReady = function () {
  70286. for (var effect in this._effects) {
  70287. if (!this._effects[effect].isReady()) {
  70288. return false;
  70289. }
  70290. }
  70291. return true;
  70292. };
  70293. return DepthOfFieldEffect;
  70294. }(BABYLON.PostProcessRenderEffect));
  70295. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70296. })(BABYLON || (BABYLON = {}));
  70297. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70298. "use strict";
  70299. var BABYLON;
  70300. (function (BABYLON) {
  70301. /**
  70302. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70303. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70304. */
  70305. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70306. __extends(DefaultRenderingPipeline, _super);
  70307. /**
  70308. * @constructor
  70309. * @param {string} name - The rendering pipeline name
  70310. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70311. * @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)
  70312. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70313. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70314. */
  70315. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70316. if (automaticBuild === void 0) { automaticBuild = true; }
  70317. var _this = _super.call(this, scene.getEngine(), name) || this;
  70318. _this._originalCameras = [];
  70319. /**
  70320. * ID of the sharpen post process,
  70321. */
  70322. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70323. /**
  70324. * ID of the pass post process used for bloom,
  70325. */
  70326. _this.PassPostProcessId = "PassPostProcessEffect";
  70327. /**
  70328. * ID of the highlight post process used for bloom,
  70329. */
  70330. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  70331. /**
  70332. * ID of the blurX post process used for bloom,
  70333. */
  70334. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  70335. /**
  70336. * ID of the blurY post process used for bloom,
  70337. */
  70338. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  70339. /**
  70340. * ID of the copy back post process used for bloom,
  70341. */
  70342. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  70343. /**
  70344. * ID of the image processing post process;
  70345. */
  70346. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70347. /**
  70348. * ID of the Fast Approximate Anti-Aliasing post process;
  70349. */
  70350. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70351. /**
  70352. * ID of the final merge post process;
  70353. */
  70354. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  70355. /**
  70356. * ID of the chromatic aberration post process,
  70357. */
  70358. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70359. /**
  70360. * Animations which can be used to tweak settings over a period of time
  70361. */
  70362. _this.animations = [];
  70363. // Values
  70364. _this._sharpenEnabled = false;
  70365. _this._bloomEnabled = false;
  70366. _this._depthOfFieldEnabled = false;
  70367. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70368. _this._fxaaEnabled = false;
  70369. _this._msaaEnabled = false;
  70370. _this._imageProcessingEnabled = true;
  70371. _this._bloomScale = 0.6;
  70372. _this._chromaticAberrationEnabled = false;
  70373. _this._buildAllowed = true;
  70374. /**
  70375. * Specifies the size of the bloom blur kernel, relative to the final output size
  70376. */
  70377. _this.bloomKernel = 64;
  70378. /**
  70379. * Specifies the weight of the bloom in the final rendering
  70380. */
  70381. _this._bloomWeight = 0.15;
  70382. _this._prevPostProcess = null;
  70383. _this._prevPrevPostProcess = null;
  70384. _this._cameras = cameras || [];
  70385. _this._originalCameras = _this._cameras.slice();
  70386. _this._buildAllowed = automaticBuild;
  70387. // Initialize
  70388. _this._scene = scene;
  70389. var caps = _this._scene.getEngine().getCaps();
  70390. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70391. // Misc
  70392. if (_this._hdr) {
  70393. if (caps.textureHalfFloatRender) {
  70394. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70395. }
  70396. else if (caps.textureFloatRender) {
  70397. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70398. }
  70399. }
  70400. else {
  70401. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70402. }
  70403. // Attach
  70404. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70405. var engine = _this._scene.getEngine();
  70406. // Create post processes before hand so they can be modified before enabled.
  70407. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70408. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70409. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70410. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70411. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70412. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70413. _this._buildPipeline();
  70414. return _this;
  70415. }
  70416. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70417. get: function () {
  70418. return this._sharpenEnabled;
  70419. },
  70420. /**
  70421. * Enable or disable the sharpen process from the pipeline
  70422. */
  70423. set: function (enabled) {
  70424. if (this._sharpenEnabled === enabled) {
  70425. return;
  70426. }
  70427. this._sharpenEnabled = enabled;
  70428. this._buildPipeline();
  70429. },
  70430. enumerable: true,
  70431. configurable: true
  70432. });
  70433. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70434. get: function () {
  70435. return this._bloomWeight;
  70436. },
  70437. /**
  70438. * The strength of the bloom.
  70439. */
  70440. set: function (value) {
  70441. if (this._bloomWeight === value) {
  70442. return;
  70443. }
  70444. this._bloomWeight = value;
  70445. if (this._hdr && this.copyBack) {
  70446. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  70447. }
  70448. },
  70449. enumerable: true,
  70450. configurable: true
  70451. });
  70452. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70453. get: function () {
  70454. return this._bloomScale;
  70455. },
  70456. /**
  70457. * The scale of the bloom, lower value will provide better performance.
  70458. */
  70459. set: function (value) {
  70460. if (this._bloomScale === value) {
  70461. return;
  70462. }
  70463. this._bloomScale = value;
  70464. this._buildPipeline();
  70465. },
  70466. enumerable: true,
  70467. configurable: true
  70468. });
  70469. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70470. get: function () {
  70471. return this._bloomEnabled;
  70472. },
  70473. /**
  70474. * Enable or disable the bloom from the pipeline
  70475. */
  70476. set: function (enabled) {
  70477. if (this._bloomEnabled === enabled) {
  70478. return;
  70479. }
  70480. this._bloomEnabled = enabled;
  70481. this._buildPipeline();
  70482. },
  70483. enumerable: true,
  70484. configurable: true
  70485. });
  70486. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  70487. /**
  70488. * If the depth of field is enabled.
  70489. */
  70490. get: function () {
  70491. return this._depthOfFieldEnabled;
  70492. },
  70493. set: function (enabled) {
  70494. if (this._depthOfFieldEnabled === enabled) {
  70495. return;
  70496. }
  70497. this._depthOfFieldEnabled = enabled;
  70498. this._buildPipeline();
  70499. },
  70500. enumerable: true,
  70501. configurable: true
  70502. });
  70503. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  70504. /**
  70505. * Blur level of the depth of field effect. (Higher blur will effect performance)
  70506. */
  70507. get: function () {
  70508. return this._depthOfFieldBlurLevel;
  70509. },
  70510. set: function (value) {
  70511. if (this._depthOfFieldBlurLevel === value) {
  70512. return;
  70513. }
  70514. this._depthOfFieldBlurLevel = value;
  70515. // recreate dof and dispose old as this setting is not dynamic
  70516. var oldDof = this.depthOfField;
  70517. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  70518. this.depthOfField.focalLength = oldDof.focalLength;
  70519. this.depthOfField.focusDistance = oldDof.focusDistance;
  70520. this.depthOfField.fStop = oldDof.fStop;
  70521. this.depthOfField.lensSize = oldDof.lensSize;
  70522. for (var i = 0; i < this._cameras.length; i++) {
  70523. oldDof.disposeEffects(this._cameras[i]);
  70524. }
  70525. this._buildPipeline();
  70526. },
  70527. enumerable: true,
  70528. configurable: true
  70529. });
  70530. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  70531. get: function () {
  70532. return this._fxaaEnabled;
  70533. },
  70534. /**
  70535. * If the anti aliasing is enabled.
  70536. */
  70537. set: function (enabled) {
  70538. if (this._fxaaEnabled === enabled) {
  70539. return;
  70540. }
  70541. this._fxaaEnabled = enabled;
  70542. this._buildPipeline();
  70543. },
  70544. enumerable: true,
  70545. configurable: true
  70546. });
  70547. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  70548. get: function () {
  70549. return this._msaaEnabled;
  70550. },
  70551. /**
  70552. * If the multisample anti-aliasing is enabled.
  70553. */
  70554. set: function (enabled) {
  70555. if (this._msaaEnabled === enabled) {
  70556. return;
  70557. }
  70558. this._msaaEnabled = enabled;
  70559. this._buildPipeline();
  70560. },
  70561. enumerable: true,
  70562. configurable: true
  70563. });
  70564. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  70565. get: function () {
  70566. return this._imageProcessingEnabled;
  70567. },
  70568. /**
  70569. * If image processing is enabled.
  70570. */
  70571. set: function (enabled) {
  70572. if (this._imageProcessingEnabled === enabled) {
  70573. return;
  70574. }
  70575. this._imageProcessingEnabled = enabled;
  70576. this._buildPipeline();
  70577. },
  70578. enumerable: true,
  70579. configurable: true
  70580. });
  70581. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  70582. get: function () {
  70583. return this._chromaticAberrationEnabled;
  70584. },
  70585. /**
  70586. * Enable or disable the chromaticAberration process from the pipeline
  70587. */
  70588. set: function (enabled) {
  70589. if (this._chromaticAberrationEnabled === enabled) {
  70590. return;
  70591. }
  70592. this._chromaticAberrationEnabled = enabled;
  70593. this._buildPipeline();
  70594. },
  70595. enumerable: true,
  70596. configurable: true
  70597. });
  70598. /**
  70599. * Force the compilation of the entire pipeline.
  70600. */
  70601. DefaultRenderingPipeline.prototype.prepare = function () {
  70602. var previousState = this._buildAllowed;
  70603. this._buildAllowed = true;
  70604. this._buildPipeline();
  70605. this._buildAllowed = previousState;
  70606. };
  70607. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  70608. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  70609. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  70610. postProcess.autoClear = false;
  70611. }
  70612. else {
  70613. postProcess.autoClear = true;
  70614. }
  70615. if (!skipTextureSharing) {
  70616. if (this._prevPrevPostProcess) {
  70617. postProcess.shareOutputWith(this._prevPrevPostProcess);
  70618. }
  70619. else {
  70620. postProcess.useOwnOutput();
  70621. }
  70622. if (this._prevPostProcess) {
  70623. this._prevPrevPostProcess = this._prevPostProcess;
  70624. }
  70625. this._prevPostProcess = postProcess;
  70626. }
  70627. };
  70628. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  70629. var _this = this;
  70630. if (!this._buildAllowed) {
  70631. return;
  70632. }
  70633. var engine = this._scene.getEngine();
  70634. this._disposePostProcesses();
  70635. if (this._cameras !== null) {
  70636. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70637. // get back cameras to be used to reattach pipeline
  70638. this._cameras = this._originalCameras.slice();
  70639. }
  70640. this._reset();
  70641. this._prevPostProcess = null;
  70642. this._prevPrevPostProcess = null;
  70643. if (this.sharpenEnabled) {
  70644. if (!this.sharpen.isReady()) {
  70645. this.sharpen.updateEffect();
  70646. }
  70647. this.addEffect(this._sharpenEffect);
  70648. this._setAutoClearAndTextureSharing(this.sharpen);
  70649. }
  70650. if (this.depthOfFieldEnabled) {
  70651. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  70652. this.depthOfField.depthTexture = depthTexture;
  70653. if (!this.depthOfField._isReady()) {
  70654. this.depthOfField._updateEffects();
  70655. }
  70656. this.addEffect(this.depthOfField);
  70657. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  70658. }
  70659. if (this.bloomEnabled) {
  70660. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70661. this._setAutoClearAndTextureSharing(this.pass, true);
  70662. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  70663. if (!this._hdr) {
  70664. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70665. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  70666. this.highlights.autoClear = false;
  70667. this.highlights.alwaysForcePOT = true;
  70668. }
  70669. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70670. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  70671. this.blurX.alwaysForcePOT = true;
  70672. this.blurX.autoClear = false;
  70673. this.blurX.onActivateObservable.add(function () {
  70674. var dw = _this.blurX.width / engine.getRenderWidth(true);
  70675. _this.blurX.kernel = _this.bloomKernel * dw;
  70676. });
  70677. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70678. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  70679. this.blurY.alwaysForcePOT = true;
  70680. this.blurY.autoClear = false;
  70681. this.blurY.onActivateObservable.add(function () {
  70682. var dh = _this.blurY.height / engine.getRenderHeight(true);
  70683. _this.blurY.kernel = _this.bloomKernel * dh;
  70684. });
  70685. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70686. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  70687. this.copyBack.alwaysForcePOT = true;
  70688. if (this._hdr) {
  70689. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  70690. var w = this.bloomWeight;
  70691. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  70692. }
  70693. else {
  70694. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  70695. }
  70696. this.copyBack.autoClear = false;
  70697. }
  70698. if (this._imageProcessingEnabled) {
  70699. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70700. if (this._hdr) {
  70701. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  70702. }
  70703. else {
  70704. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  70705. }
  70706. }
  70707. if (this._hdr && this.imageProcessing) {
  70708. this.finalMerge = this.imageProcessing;
  70709. }
  70710. else {
  70711. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70712. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  70713. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  70714. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  70715. }
  70716. if (this.bloomEnabled) {
  70717. if (this._hdr) {
  70718. this.copyBack.shareOutputWith(this.blurX);
  70719. if (this.imageProcessing) {
  70720. this.imageProcessing.shareOutputWith(this.pass);
  70721. this.imageProcessing.autoClear = false;
  70722. }
  70723. else {
  70724. this.finalMerge.shareOutputWith(this.pass);
  70725. }
  70726. }
  70727. else {
  70728. this.finalMerge.shareOutputWith(this.pass);
  70729. }
  70730. }
  70731. if (this.fxaaEnabled) {
  70732. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70733. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  70734. this._setAutoClearAndTextureSharing(this.fxaa);
  70735. }
  70736. if (this.chromaticAberrationEnabled) {
  70737. if (!this.chromaticAberration.isReady()) {
  70738. this.chromaticAberration.updateEffect();
  70739. }
  70740. this.addEffect(this._chromaticAberrationEffect);
  70741. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  70742. }
  70743. if (this._cameras !== null) {
  70744. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  70745. }
  70746. if (this.msaaEnabled) {
  70747. if (!this._enableMSAAOnFirstPostProcess()) {
  70748. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  70749. }
  70750. }
  70751. };
  70752. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  70753. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  70754. for (var i = 0; i < this._cameras.length; i++) {
  70755. var camera = this._cameras[i];
  70756. if (this.pass) {
  70757. this.pass.dispose(camera);
  70758. }
  70759. if (this.highlights) {
  70760. this.highlights.dispose(camera);
  70761. }
  70762. if (this.blurX) {
  70763. this.blurX.dispose(camera);
  70764. }
  70765. if (this.blurY) {
  70766. this.blurY.dispose(camera);
  70767. }
  70768. if (this.copyBack) {
  70769. this.copyBack.dispose(camera);
  70770. }
  70771. if (this.imageProcessing) {
  70772. this.imageProcessing.dispose(camera);
  70773. }
  70774. if (this.fxaa) {
  70775. this.fxaa.dispose(camera);
  70776. }
  70777. if (this.finalMerge) {
  70778. this.finalMerge.dispose(camera);
  70779. }
  70780. // These are created in the constructor and should not be disposed on every pipeline change
  70781. if (disposeNonRecreated) {
  70782. if (this.sharpen) {
  70783. this.sharpen.dispose(camera);
  70784. }
  70785. if (this.depthOfField) {
  70786. this.depthOfField.disposeEffects(camera);
  70787. }
  70788. if (this.chromaticAberration) {
  70789. this.chromaticAberration.dispose(camera);
  70790. }
  70791. }
  70792. }
  70793. this.pass = null;
  70794. this.highlights = null;
  70795. this.blurX = null;
  70796. this.blurY = null;
  70797. this.copyBack = null;
  70798. this.imageProcessing = null;
  70799. this.fxaa = null;
  70800. this.finalMerge = null;
  70801. if (disposeNonRecreated) {
  70802. this.sharpen = null;
  70803. this.depthOfField = null;
  70804. this.chromaticAberration = null;
  70805. }
  70806. };
  70807. /**
  70808. * Dispose of the pipeline and stop all post processes
  70809. */
  70810. DefaultRenderingPipeline.prototype.dispose = function () {
  70811. this._disposePostProcesses(true);
  70812. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70813. _super.prototype.dispose.call(this);
  70814. };
  70815. /**
  70816. * Serialize the rendering pipeline (Used when exporting)
  70817. * @returns the serialized object
  70818. */
  70819. DefaultRenderingPipeline.prototype.serialize = function () {
  70820. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70821. serializationObject.customType = "DefaultRenderingPipeline";
  70822. return serializationObject;
  70823. };
  70824. /**
  70825. * Parse the serialized pipeline
  70826. * @param source Source pipeline.
  70827. * @param scene The scene to load the pipeline to.
  70828. * @param rootUrl The URL of the serialized pipeline.
  70829. * @returns An instantiated pipeline from the serialized object.
  70830. */
  70831. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70832. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  70833. };
  70834. __decorate([
  70835. BABYLON.serialize()
  70836. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  70837. __decorate([
  70838. BABYLON.serialize()
  70839. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  70840. __decorate([
  70841. BABYLON.serialize()
  70842. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  70843. __decorate([
  70844. BABYLON.serialize()
  70845. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  70846. __decorate([
  70847. BABYLON.serialize()
  70848. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  70849. __decorate([
  70850. BABYLON.serialize()
  70851. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  70852. __decorate([
  70853. BABYLON.serialize()
  70854. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  70855. __decorate([
  70856. BABYLON.serialize()
  70857. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  70858. __decorate([
  70859. BABYLON.serialize()
  70860. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  70861. __decorate([
  70862. BABYLON.serialize()
  70863. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  70864. __decorate([
  70865. BABYLON.serialize()
  70866. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  70867. __decorate([
  70868. BABYLON.serialize()
  70869. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  70870. __decorate([
  70871. BABYLON.serialize()
  70872. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  70873. return DefaultRenderingPipeline;
  70874. }(BABYLON.PostProcessRenderPipeline));
  70875. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  70876. })(BABYLON || (BABYLON = {}));
  70877. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  70878. "use strict";
  70879. var BABYLON;
  70880. (function (BABYLON) {
  70881. /**
  70882. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  70883. */
  70884. var GeometryBufferRenderer = /** @class */ (function () {
  70885. /**
  70886. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  70887. * @param scene The scene the buffer belongs to
  70888. * @param ratio How big is the buffer related to the main canvas.
  70889. */
  70890. function GeometryBufferRenderer(scene, ratio) {
  70891. if (ratio === void 0) { ratio = 1; }
  70892. this._enablePosition = false;
  70893. this._scene = scene;
  70894. this._ratio = ratio;
  70895. // Render target
  70896. this._createRenderTargets();
  70897. }
  70898. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70899. /**
  70900. * Set the render list (meshes to be rendered) used in the G buffer.
  70901. */
  70902. set: function (meshes) {
  70903. this._multiRenderTarget.renderList = meshes;
  70904. },
  70905. enumerable: true,
  70906. configurable: true
  70907. });
  70908. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70909. /**
  70910. * Gets wether or not G buffer are supported by the running hardware.
  70911. * This requires draw buffer supports
  70912. */
  70913. get: function () {
  70914. return this._multiRenderTarget.isSupported;
  70915. },
  70916. enumerable: true,
  70917. configurable: true
  70918. });
  70919. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70920. /**
  70921. * Gets wether or not position are enabled for the G buffer.
  70922. */
  70923. get: function () {
  70924. return this._enablePosition;
  70925. },
  70926. /**
  70927. * Sets wether or not position are enabled for the G buffer.
  70928. */
  70929. set: function (enable) {
  70930. this._enablePosition = enable;
  70931. this.dispose();
  70932. this._createRenderTargets();
  70933. },
  70934. enumerable: true,
  70935. configurable: true
  70936. });
  70937. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70938. /**
  70939. * Gets the scene associated with the buffer.
  70940. */
  70941. get: function () {
  70942. return this._scene;
  70943. },
  70944. enumerable: true,
  70945. configurable: true
  70946. });
  70947. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70948. /**
  70949. * Gets the ratio used by the buffer during its creation.
  70950. * How big is the buffer related to the main canvas.
  70951. */
  70952. get: function () {
  70953. return this._ratio;
  70954. },
  70955. enumerable: true,
  70956. configurable: true
  70957. });
  70958. /**
  70959. * Checks wether everything is ready to render a submesh to the G buffer.
  70960. * @param subMesh the submesh to check readiness for
  70961. * @param useInstances is the mesh drawn using instance or not
  70962. * @returns true if ready otherwise false
  70963. */
  70964. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70965. var material = subMesh.getMaterial();
  70966. if (material && material.disableDepthWrite) {
  70967. return false;
  70968. }
  70969. var defines = [];
  70970. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70971. var mesh = subMesh.getMesh();
  70972. // Alpha test
  70973. if (material && material.needAlphaTesting()) {
  70974. defines.push("#define ALPHATEST");
  70975. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70976. attribs.push(BABYLON.VertexBuffer.UVKind);
  70977. defines.push("#define UV1");
  70978. }
  70979. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70980. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70981. defines.push("#define UV2");
  70982. }
  70983. }
  70984. // Buffers
  70985. if (this._enablePosition) {
  70986. defines.push("#define POSITION");
  70987. }
  70988. // Bones
  70989. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70990. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70991. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70992. if (mesh.numBoneInfluencers > 4) {
  70993. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70994. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70995. }
  70996. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70997. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70998. }
  70999. else {
  71000. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71001. }
  71002. // Instances
  71003. if (useInstances) {
  71004. defines.push("#define INSTANCES");
  71005. attribs.push("world0");
  71006. attribs.push("world1");
  71007. attribs.push("world2");
  71008. attribs.push("world3");
  71009. }
  71010. // Get correct effect
  71011. var join = defines.join("\n");
  71012. if (this._cachedDefines !== join) {
  71013. this._cachedDefines = join;
  71014. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  71015. }
  71016. return this._effect.isReady();
  71017. };
  71018. /**
  71019. * Gets the current underlying G Buffer.
  71020. * @returns the buffer
  71021. */
  71022. GeometryBufferRenderer.prototype.getGBuffer = function () {
  71023. return this._multiRenderTarget;
  71024. };
  71025. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  71026. /**
  71027. * Gets the number of samples used to render the buffer (anti aliasing).
  71028. */
  71029. get: function () {
  71030. return this._multiRenderTarget.samples;
  71031. },
  71032. /**
  71033. * Sets the number of samples used to render the buffer (anti aliasing).
  71034. */
  71035. set: function (value) {
  71036. this._multiRenderTarget.samples = value;
  71037. },
  71038. enumerable: true,
  71039. configurable: true
  71040. });
  71041. /**
  71042. * Disposes the renderer and frees up associated resources.
  71043. */
  71044. GeometryBufferRenderer.prototype.dispose = function () {
  71045. this.getGBuffer().dispose();
  71046. };
  71047. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71048. var _this = this;
  71049. var engine = this._scene.getEngine();
  71050. var count = this._enablePosition ? 3 : 2;
  71051. 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 });
  71052. if (!this.isSupported) {
  71053. return;
  71054. }
  71055. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71056. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71057. this._multiRenderTarget.refreshRate = 1;
  71058. this._multiRenderTarget.renderParticles = false;
  71059. this._multiRenderTarget.renderList = null;
  71060. // set default depth value to 1.0 (far away)
  71061. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71062. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71063. });
  71064. // Custom render function
  71065. var renderSubMesh = function (subMesh) {
  71066. var mesh = subMesh.getRenderingMesh();
  71067. var scene = _this._scene;
  71068. var engine = scene.getEngine();
  71069. var material = subMesh.getMaterial();
  71070. if (!material) {
  71071. return;
  71072. }
  71073. // Culling
  71074. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71075. // Managing instances
  71076. var batch = mesh._getInstancesRenderList(subMesh._id);
  71077. if (batch.mustReturn) {
  71078. return;
  71079. }
  71080. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71081. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71082. engine.enableEffect(_this._effect);
  71083. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71084. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71085. _this._effect.setMatrix("view", scene.getViewMatrix());
  71086. // Alpha test
  71087. if (material && material.needAlphaTesting()) {
  71088. var alphaTexture = material.getAlphaTestTexture();
  71089. if (alphaTexture) {
  71090. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71091. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71092. }
  71093. }
  71094. // Bones
  71095. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71096. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71097. }
  71098. // Draw
  71099. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71100. }
  71101. };
  71102. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71103. var index;
  71104. if (depthOnlySubMeshes.length) {
  71105. engine.setColorWrite(false);
  71106. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71107. renderSubMesh(depthOnlySubMeshes.data[index]);
  71108. }
  71109. engine.setColorWrite(true);
  71110. }
  71111. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71112. renderSubMesh(opaqueSubMeshes.data[index]);
  71113. }
  71114. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71115. renderSubMesh(alphaTestSubMeshes.data[index]);
  71116. }
  71117. };
  71118. };
  71119. return GeometryBufferRenderer;
  71120. }());
  71121. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71122. })(BABYLON || (BABYLON = {}));
  71123. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71124. "use strict";
  71125. var BABYLON;
  71126. (function (BABYLON) {
  71127. var RefractionPostProcess = /** @class */ (function (_super) {
  71128. __extends(RefractionPostProcess, _super);
  71129. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71130. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71131. _this.color = color;
  71132. _this.depth = depth;
  71133. _this.colorLevel = colorLevel;
  71134. _this._ownRefractionTexture = true;
  71135. _this.onActivateObservable.add(function (cam) {
  71136. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71137. });
  71138. _this.onApplyObservable.add(function (effect) {
  71139. effect.setColor3("baseColor", _this.color);
  71140. effect.setFloat("depth", _this.depth);
  71141. effect.setFloat("colorLevel", _this.colorLevel);
  71142. effect.setTexture("refractionSampler", _this._refTexture);
  71143. });
  71144. return _this;
  71145. }
  71146. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71147. /**
  71148. * Gets or sets the refraction texture
  71149. * Please note that you are responsible for disposing the texture if you set it manually
  71150. */
  71151. get: function () {
  71152. return this._refTexture;
  71153. },
  71154. set: function (value) {
  71155. if (this._refTexture && this._ownRefractionTexture) {
  71156. this._refTexture.dispose();
  71157. }
  71158. this._refTexture = value;
  71159. this._ownRefractionTexture = false;
  71160. },
  71161. enumerable: true,
  71162. configurable: true
  71163. });
  71164. // Methods
  71165. RefractionPostProcess.prototype.dispose = function (camera) {
  71166. if (this._refTexture && this._ownRefractionTexture) {
  71167. this._refTexture.dispose();
  71168. this._refTexture = null;
  71169. }
  71170. _super.prototype.dispose.call(this, camera);
  71171. };
  71172. return RefractionPostProcess;
  71173. }(BABYLON.PostProcess));
  71174. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71175. })(BABYLON || (BABYLON = {}));
  71176. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71177. "use strict";
  71178. var BABYLON;
  71179. (function (BABYLON) {
  71180. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71181. __extends(BlackAndWhitePostProcess, _super);
  71182. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71183. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71184. _this.degree = 1;
  71185. _this.onApplyObservable.add(function (effect) {
  71186. effect.setFloat("degree", _this.degree);
  71187. });
  71188. return _this;
  71189. }
  71190. return BlackAndWhitePostProcess;
  71191. }(BABYLON.PostProcess));
  71192. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71193. })(BABYLON || (BABYLON = {}));
  71194. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71195. "use strict";
  71196. var BABYLON;
  71197. (function (BABYLON) {
  71198. /**
  71199. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71200. * input texture to perform effects such as edge detection or sharpening
  71201. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71202. */
  71203. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71204. __extends(ConvolutionPostProcess, _super);
  71205. /**
  71206. * Creates a new instance of @see ConvolutionPostProcess
  71207. * @param name The name of the effect.
  71208. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71209. * @param options The required width/height ratio to downsize to before computing the render pass.
  71210. * @param camera The camera to apply the render pass to.
  71211. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71212. * @param engine The engine which the post process will be applied. (default: current engine)
  71213. * @param reusable If the post process can be reused on the same frame. (default: false)
  71214. * @param textureType Type of textures used when performing the post process. (default: 0)
  71215. */
  71216. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71217. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71218. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71219. _this.kernel = kernel;
  71220. _this.onApply = function (effect) {
  71221. effect.setFloat2("screenSize", _this.width, _this.height);
  71222. effect.setArray("kernel", _this.kernel);
  71223. };
  71224. return _this;
  71225. }
  71226. // Statics
  71227. /**
  71228. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71229. */
  71230. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71231. /**
  71232. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71233. */
  71234. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71235. /**
  71236. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71237. */
  71238. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71239. /**
  71240. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71241. */
  71242. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71243. /**
  71244. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71245. */
  71246. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71247. /**
  71248. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71249. */
  71250. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71251. return ConvolutionPostProcess;
  71252. }(BABYLON.PostProcess));
  71253. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71254. })(BABYLON || (BABYLON = {}));
  71255. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71256. "use strict";
  71257. var BABYLON;
  71258. (function (BABYLON) {
  71259. var FilterPostProcess = /** @class */ (function (_super) {
  71260. __extends(FilterPostProcess, _super);
  71261. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71262. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71263. _this.kernelMatrix = kernelMatrix;
  71264. _this.onApply = function (effect) {
  71265. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71266. };
  71267. return _this;
  71268. }
  71269. return FilterPostProcess;
  71270. }(BABYLON.PostProcess));
  71271. BABYLON.FilterPostProcess = FilterPostProcess;
  71272. })(BABYLON || (BABYLON = {}));
  71273. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71274. "use strict";
  71275. var BABYLON;
  71276. (function (BABYLON) {
  71277. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71278. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71279. __extends(VolumetricLightScatteringPostProcess, _super);
  71280. /**
  71281. * @constructor
  71282. * @param {string} name - The post-process name
  71283. * @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)
  71284. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71285. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71286. * @param {number} samples - The post-process quality, default 100
  71287. * @param {number} samplingMode - The post-process filtering mode
  71288. * @param {BABYLON.Engine} engine - The babylon engine
  71289. * @param {boolean} reusable - If the post-process is reusable
  71290. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71291. */
  71292. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71293. if (samples === void 0) { samples = 100; }
  71294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71295. 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;
  71296. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71297. /**
  71298. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71299. * @type {Vector3}
  71300. */
  71301. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71302. /**
  71303. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71304. * @type {boolean}
  71305. */
  71306. _this.useCustomMeshPosition = false;
  71307. /**
  71308. * If the post-process should inverse the light scattering direction
  71309. * @type {boolean}
  71310. */
  71311. _this.invert = true;
  71312. /**
  71313. * Array containing the excluded meshes not rendered in the internal pass
  71314. */
  71315. _this.excludedMeshes = new Array();
  71316. /**
  71317. * Controls the overall intensity of the post-process
  71318. * @type {number}
  71319. */
  71320. _this.exposure = 0.3;
  71321. /**
  71322. * Dissipates each sample's contribution in range [0, 1]
  71323. * @type {number}
  71324. */
  71325. _this.decay = 0.96815;
  71326. /**
  71327. * Controls the overall intensity of each sample
  71328. * @type {number}
  71329. */
  71330. _this.weight = 0.58767;
  71331. /**
  71332. * Controls the density of each sample
  71333. * @type {number}
  71334. */
  71335. _this.density = 0.926;
  71336. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71337. engine = scene.getEngine();
  71338. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71339. // Configure mesh
  71340. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71341. // Configure
  71342. _this._createPass(scene, ratio.passRatio || ratio);
  71343. _this.onActivate = function (camera) {
  71344. if (!_this.isSupported) {
  71345. _this.dispose(camera);
  71346. }
  71347. _this.onActivate = null;
  71348. };
  71349. _this.onApplyObservable.add(function (effect) {
  71350. _this._updateMeshScreenCoordinates(scene);
  71351. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71352. effect.setFloat("exposure", _this.exposure);
  71353. effect.setFloat("decay", _this.decay);
  71354. effect.setFloat("weight", _this.weight);
  71355. effect.setFloat("density", _this.density);
  71356. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71357. });
  71358. return _this;
  71359. }
  71360. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71361. get: function () {
  71362. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71363. return false;
  71364. },
  71365. set: function (useDiffuseColor) {
  71366. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71367. },
  71368. enumerable: true,
  71369. configurable: true
  71370. });
  71371. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71372. return "VolumetricLightScatteringPostProcess";
  71373. };
  71374. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71375. var mesh = subMesh.getMesh();
  71376. // Render this.mesh as default
  71377. if (mesh === this.mesh && mesh.material) {
  71378. return mesh.material.isReady(mesh);
  71379. }
  71380. var defines = [];
  71381. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71382. var material = subMesh.getMaterial();
  71383. // Alpha test
  71384. if (material) {
  71385. if (material.needAlphaTesting()) {
  71386. defines.push("#define ALPHATEST");
  71387. }
  71388. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71389. attribs.push(BABYLON.VertexBuffer.UVKind);
  71390. defines.push("#define UV1");
  71391. }
  71392. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71393. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71394. defines.push("#define UV2");
  71395. }
  71396. }
  71397. // Bones
  71398. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71399. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71400. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71401. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71402. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71403. }
  71404. else {
  71405. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71406. }
  71407. // Instances
  71408. if (useInstances) {
  71409. defines.push("#define INSTANCES");
  71410. attribs.push("world0");
  71411. attribs.push("world1");
  71412. attribs.push("world2");
  71413. attribs.push("world3");
  71414. }
  71415. // Get correct effect
  71416. var join = defines.join("\n");
  71417. if (this._cachedDefines !== join) {
  71418. this._cachedDefines = join;
  71419. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71420. }
  71421. return this._volumetricLightScatteringPass.isReady();
  71422. };
  71423. /**
  71424. * Sets the new light position for light scattering effect
  71425. * @param {BABYLON.Vector3} The new custom light position
  71426. */
  71427. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71428. this.customMeshPosition = position;
  71429. };
  71430. /**
  71431. * Returns the light position for light scattering effect
  71432. * @return {BABYLON.Vector3} The custom light position
  71433. */
  71434. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71435. return this.customMeshPosition;
  71436. };
  71437. /**
  71438. * Disposes the internal assets and detaches the post-process from the camera
  71439. */
  71440. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71441. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71442. if (rttIndex !== -1) {
  71443. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71444. }
  71445. this._volumetricLightScatteringRTT.dispose();
  71446. _super.prototype.dispose.call(this, camera);
  71447. };
  71448. /**
  71449. * Returns the render target texture used by the post-process
  71450. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71451. */
  71452. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71453. return this._volumetricLightScatteringRTT;
  71454. };
  71455. // Private methods
  71456. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71457. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71458. return true;
  71459. }
  71460. return false;
  71461. };
  71462. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71463. var _this = this;
  71464. var engine = scene.getEngine();
  71465. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71466. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71467. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71468. this._volumetricLightScatteringRTT.renderList = null;
  71469. this._volumetricLightScatteringRTT.renderParticles = false;
  71470. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71471. var camera = this.getCamera();
  71472. if (camera) {
  71473. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71474. }
  71475. else {
  71476. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71477. }
  71478. // Custom render function for submeshes
  71479. var renderSubMesh = function (subMesh) {
  71480. var mesh = subMesh.getRenderingMesh();
  71481. if (_this._meshExcluded(mesh)) {
  71482. return;
  71483. }
  71484. var material = subMesh.getMaterial();
  71485. if (!material) {
  71486. return;
  71487. }
  71488. var scene = mesh.getScene();
  71489. var engine = scene.getEngine();
  71490. // Culling
  71491. engine.setState(material.backFaceCulling);
  71492. // Managing instances
  71493. var batch = mesh._getInstancesRenderList(subMesh._id);
  71494. if (batch.mustReturn) {
  71495. return;
  71496. }
  71497. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71498. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71499. var effect = _this._volumetricLightScatteringPass;
  71500. if (mesh === _this.mesh) {
  71501. if (subMesh.effect) {
  71502. effect = subMesh.effect;
  71503. }
  71504. else {
  71505. effect = material.getEffect();
  71506. }
  71507. }
  71508. engine.enableEffect(effect);
  71509. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  71510. if (mesh === _this.mesh) {
  71511. material.bind(mesh.getWorldMatrix(), mesh);
  71512. }
  71513. else {
  71514. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  71515. // Alpha test
  71516. if (material && material.needAlphaTesting()) {
  71517. var alphaTexture = material.getAlphaTestTexture();
  71518. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  71519. if (alphaTexture) {
  71520. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71521. }
  71522. }
  71523. // Bones
  71524. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71525. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71526. }
  71527. }
  71528. // Draw
  71529. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  71530. }
  71531. };
  71532. // Render target texture callbacks
  71533. var savedSceneClearColor;
  71534. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  71535. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  71536. savedSceneClearColor = scene.clearColor;
  71537. scene.clearColor = sceneClearColor;
  71538. });
  71539. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  71540. scene.clearColor = savedSceneClearColor;
  71541. });
  71542. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71543. var engine = scene.getEngine();
  71544. var index;
  71545. if (depthOnlySubMeshes.length) {
  71546. engine.setColorWrite(false);
  71547. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71548. renderSubMesh(depthOnlySubMeshes.data[index]);
  71549. }
  71550. engine.setColorWrite(true);
  71551. }
  71552. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71553. renderSubMesh(opaqueSubMeshes.data[index]);
  71554. }
  71555. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71556. renderSubMesh(alphaTestSubMeshes.data[index]);
  71557. }
  71558. if (transparentSubMeshes.length) {
  71559. // Sort sub meshes
  71560. for (index = 0; index < transparentSubMeshes.length; index++) {
  71561. var submesh = transparentSubMeshes.data[index];
  71562. var boundingInfo = submesh.getBoundingInfo();
  71563. if (boundingInfo && scene.activeCamera) {
  71564. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  71565. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  71566. }
  71567. }
  71568. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  71569. sortedArray.sort(function (a, b) {
  71570. // Alpha index first
  71571. if (a._alphaIndex > b._alphaIndex) {
  71572. return 1;
  71573. }
  71574. if (a._alphaIndex < b._alphaIndex) {
  71575. return -1;
  71576. }
  71577. // Then distance to camera
  71578. if (a._distanceToCamera < b._distanceToCamera) {
  71579. return 1;
  71580. }
  71581. if (a._distanceToCamera > b._distanceToCamera) {
  71582. return -1;
  71583. }
  71584. return 0;
  71585. });
  71586. // Render sub meshes
  71587. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  71588. for (index = 0; index < sortedArray.length; index++) {
  71589. renderSubMesh(sortedArray[index]);
  71590. }
  71591. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71592. }
  71593. };
  71594. };
  71595. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  71596. var transform = scene.getTransformMatrix();
  71597. var meshPosition;
  71598. if (this.useCustomMeshPosition) {
  71599. meshPosition = this.customMeshPosition;
  71600. }
  71601. else if (this.attachedNode) {
  71602. meshPosition = this.attachedNode.position;
  71603. }
  71604. else {
  71605. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  71606. }
  71607. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  71608. this._screenCoordinates.x = pos.x / this._viewPort.width;
  71609. this._screenCoordinates.y = pos.y / this._viewPort.height;
  71610. if (this.invert)
  71611. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  71612. };
  71613. // Static methods
  71614. /**
  71615. * Creates a default mesh for the Volumeric Light Scattering post-process
  71616. * @param {string} The mesh name
  71617. * @param {BABYLON.Scene} The scene where to create the mesh
  71618. * @return {BABYLON.Mesh} the default mesh
  71619. */
  71620. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  71621. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  71622. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  71623. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  71624. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  71625. mesh.material = material;
  71626. return mesh;
  71627. };
  71628. __decorate([
  71629. BABYLON.serializeAsVector3()
  71630. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  71631. __decorate([
  71632. BABYLON.serialize()
  71633. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  71634. __decorate([
  71635. BABYLON.serialize()
  71636. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  71637. __decorate([
  71638. BABYLON.serializeAsMeshReference()
  71639. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  71640. __decorate([
  71641. BABYLON.serialize()
  71642. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  71643. __decorate([
  71644. BABYLON.serialize()
  71645. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  71646. __decorate([
  71647. BABYLON.serialize()
  71648. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  71649. __decorate([
  71650. BABYLON.serialize()
  71651. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  71652. __decorate([
  71653. BABYLON.serialize()
  71654. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  71655. return VolumetricLightScatteringPostProcess;
  71656. }(BABYLON.PostProcess));
  71657. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  71658. })(BABYLON || (BABYLON = {}));
  71659. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  71660. "use strict";
  71661. //
  71662. // This post-process allows the modification of rendered colors by using
  71663. // a 'look-up table' (LUT). This effect is also called Color Grading.
  71664. //
  71665. // The object needs to be provided an url to a texture containing the color
  71666. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  71667. // Use an image editing software to tweak the LUT to match your needs.
  71668. //
  71669. // For an example of a color LUT, see here:
  71670. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  71671. // For explanations on color grading, see here:
  71672. // http://udn.epicgames.com/Three/ColorGrading.html
  71673. //
  71674. var BABYLON;
  71675. (function (BABYLON) {
  71676. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  71677. __extends(ColorCorrectionPostProcess, _super);
  71678. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  71679. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  71680. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71681. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  71682. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71683. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71684. _this.onApply = function (effect) {
  71685. effect.setTexture("colorTable", _this._colorTableTexture);
  71686. };
  71687. return _this;
  71688. }
  71689. return ColorCorrectionPostProcess;
  71690. }(BABYLON.PostProcess));
  71691. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  71692. })(BABYLON || (BABYLON = {}));
  71693. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  71694. "use strict";
  71695. var BABYLON;
  71696. (function (BABYLON) {
  71697. var TonemappingOperator;
  71698. (function (TonemappingOperator) {
  71699. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  71700. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  71701. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  71702. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  71703. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  71704. ;
  71705. var TonemapPostProcess = /** @class */ (function (_super) {
  71706. __extends(TonemapPostProcess, _super);
  71707. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  71708. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71709. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71710. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  71711. _this._operator = _operator;
  71712. _this.exposureAdjustment = exposureAdjustment;
  71713. var defines = "#define ";
  71714. if (_this._operator === TonemappingOperator.Hable)
  71715. defines += "HABLE_TONEMAPPING";
  71716. else if (_this._operator === TonemappingOperator.Reinhard)
  71717. defines += "REINHARD_TONEMAPPING";
  71718. else if (_this._operator === TonemappingOperator.HejiDawson)
  71719. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  71720. else if (_this._operator === TonemappingOperator.Photographic)
  71721. defines += "PHOTOGRAPHIC_TONEMAPPING";
  71722. //sadly a second call to create the effect.
  71723. _this.updateEffect(defines);
  71724. _this.onApply = function (effect) {
  71725. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  71726. };
  71727. return _this;
  71728. }
  71729. return TonemapPostProcess;
  71730. }(BABYLON.PostProcess));
  71731. BABYLON.TonemapPostProcess = TonemapPostProcess;
  71732. })(BABYLON || (BABYLON = {}));
  71733. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  71734. "use strict";
  71735. var BABYLON;
  71736. (function (BABYLON) {
  71737. var DisplayPassPostProcess = /** @class */ (function (_super) {
  71738. __extends(DisplayPassPostProcess, _super);
  71739. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  71740. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  71741. }
  71742. return DisplayPassPostProcess;
  71743. }(BABYLON.PostProcess));
  71744. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  71745. })(BABYLON || (BABYLON = {}));
  71746. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  71747. "use strict";
  71748. var BABYLON;
  71749. (function (BABYLON) {
  71750. var HighlightsPostProcess = /** @class */ (function (_super) {
  71751. __extends(HighlightsPostProcess, _super);
  71752. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  71753. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71754. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71755. }
  71756. return HighlightsPostProcess;
  71757. }(BABYLON.PostProcess));
  71758. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  71759. })(BABYLON || (BABYLON = {}));
  71760. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  71761. "use strict";
  71762. var BABYLON;
  71763. (function (BABYLON) {
  71764. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  71765. __extends(ImageProcessingPostProcess, _super);
  71766. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  71767. if (camera === void 0) { camera = null; }
  71768. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71769. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  71770. _this._fromLinearSpace = true;
  71771. /**
  71772. * Defines cache preventing GC.
  71773. */
  71774. _this._defines = {
  71775. IMAGEPROCESSING: false,
  71776. VIGNETTE: false,
  71777. VIGNETTEBLENDMODEMULTIPLY: false,
  71778. VIGNETTEBLENDMODEOPAQUE: false,
  71779. TONEMAPPING: false,
  71780. CONTRAST: false,
  71781. COLORCURVES: false,
  71782. COLORGRADING: false,
  71783. COLORGRADING3D: false,
  71784. FROMLINEARSPACE: false,
  71785. SAMPLER3DGREENDEPTH: false,
  71786. SAMPLER3DBGRMAP: false,
  71787. IMAGEPROCESSINGPOSTPROCESS: false,
  71788. EXPOSURE: false,
  71789. GRAIN: false,
  71790. };
  71791. // Setup the configuration as forced by the constructor. This would then not force the
  71792. // scene materials output in linear space and let untouched the default forward pass.
  71793. if (imageProcessingConfiguration) {
  71794. imageProcessingConfiguration.applyByPostProcess = true;
  71795. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  71796. // This will cause the shader to be compiled
  71797. _this.fromLinearSpace = false;
  71798. }
  71799. else {
  71800. _this._attachImageProcessingConfiguration(null, true);
  71801. _this.imageProcessingConfiguration.applyByPostProcess = true;
  71802. }
  71803. _this.onApply = function (effect) {
  71804. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  71805. };
  71806. return _this;
  71807. }
  71808. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  71809. /**
  71810. * Gets the image processing configuration used either in this material.
  71811. */
  71812. get: function () {
  71813. return this._imageProcessingConfiguration;
  71814. },
  71815. /**
  71816. * Sets the Default image processing configuration used either in the this material.
  71817. *
  71818. * If sets to null, the scene one is in use.
  71819. */
  71820. set: function (value) {
  71821. this._attachImageProcessingConfiguration(value);
  71822. },
  71823. enumerable: true,
  71824. configurable: true
  71825. });
  71826. /**
  71827. * Attaches a new image processing configuration to the PBR Material.
  71828. * @param configuration
  71829. */
  71830. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  71831. var _this = this;
  71832. if (doNotBuild === void 0) { doNotBuild = false; }
  71833. if (configuration === this._imageProcessingConfiguration) {
  71834. return;
  71835. }
  71836. // Detaches observer.
  71837. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71838. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71839. }
  71840. // Pick the scene configuration if needed.
  71841. if (!configuration) {
  71842. var scene = null;
  71843. var engine = this.getEngine();
  71844. var camera = this.getCamera();
  71845. if (camera) {
  71846. scene = camera.getScene();
  71847. }
  71848. else if (engine && engine.scenes) {
  71849. var scenes = engine.scenes;
  71850. scene = scenes[scenes.length - 1];
  71851. }
  71852. else {
  71853. scene = BABYLON.Engine.LastCreatedScene;
  71854. }
  71855. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  71856. }
  71857. else {
  71858. this._imageProcessingConfiguration = configuration;
  71859. }
  71860. // Attaches observer.
  71861. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  71862. _this._updateParameters();
  71863. });
  71864. // Ensure the effect will be rebuilt.
  71865. if (!doNotBuild) {
  71866. this._updateParameters();
  71867. }
  71868. };
  71869. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  71870. /**
  71871. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71872. */
  71873. get: function () {
  71874. return this.imageProcessingConfiguration.colorCurves;
  71875. },
  71876. /**
  71877. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71878. */
  71879. set: function (value) {
  71880. this.imageProcessingConfiguration.colorCurves = value;
  71881. },
  71882. enumerable: true,
  71883. configurable: true
  71884. });
  71885. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  71886. /**
  71887. * Gets wether the color curves effect is enabled.
  71888. */
  71889. get: function () {
  71890. return this.imageProcessingConfiguration.colorCurvesEnabled;
  71891. },
  71892. /**
  71893. * Sets wether the color curves effect is enabled.
  71894. */
  71895. set: function (value) {
  71896. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  71897. },
  71898. enumerable: true,
  71899. configurable: true
  71900. });
  71901. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  71902. /**
  71903. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71904. */
  71905. get: function () {
  71906. return this.imageProcessingConfiguration.colorGradingTexture;
  71907. },
  71908. /**
  71909. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71910. */
  71911. set: function (value) {
  71912. this.imageProcessingConfiguration.colorGradingTexture = value;
  71913. },
  71914. enumerable: true,
  71915. configurable: true
  71916. });
  71917. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71918. /**
  71919. * Gets wether the color grading effect is enabled.
  71920. */
  71921. get: function () {
  71922. return this.imageProcessingConfiguration.colorGradingEnabled;
  71923. },
  71924. /**
  71925. * Gets wether the color grading effect is enabled.
  71926. */
  71927. set: function (value) {
  71928. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71929. },
  71930. enumerable: true,
  71931. configurable: true
  71932. });
  71933. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71934. /**
  71935. * Gets exposure used in the effect.
  71936. */
  71937. get: function () {
  71938. return this.imageProcessingConfiguration.exposure;
  71939. },
  71940. /**
  71941. * Sets exposure used in the effect.
  71942. */
  71943. set: function (value) {
  71944. this.imageProcessingConfiguration.exposure = value;
  71945. },
  71946. enumerable: true,
  71947. configurable: true
  71948. });
  71949. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71950. /**
  71951. * Gets wether tonemapping is enabled or not.
  71952. */
  71953. get: function () {
  71954. return this._imageProcessingConfiguration.toneMappingEnabled;
  71955. },
  71956. /**
  71957. * Sets wether tonemapping is enabled or not
  71958. */
  71959. set: function (value) {
  71960. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71961. },
  71962. enumerable: true,
  71963. configurable: true
  71964. });
  71965. ;
  71966. ;
  71967. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71968. /**
  71969. * Gets contrast used in the effect.
  71970. */
  71971. get: function () {
  71972. return this.imageProcessingConfiguration.contrast;
  71973. },
  71974. /**
  71975. * Sets contrast used in the effect.
  71976. */
  71977. set: function (value) {
  71978. this.imageProcessingConfiguration.contrast = value;
  71979. },
  71980. enumerable: true,
  71981. configurable: true
  71982. });
  71983. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71984. /**
  71985. * Gets Vignette stretch size.
  71986. */
  71987. get: function () {
  71988. return this.imageProcessingConfiguration.vignetteStretch;
  71989. },
  71990. /**
  71991. * Sets Vignette stretch size.
  71992. */
  71993. set: function (value) {
  71994. this.imageProcessingConfiguration.vignetteStretch = value;
  71995. },
  71996. enumerable: true,
  71997. configurable: true
  71998. });
  71999. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  72000. /**
  72001. * Gets Vignette centre X Offset.
  72002. */
  72003. get: function () {
  72004. return this.imageProcessingConfiguration.vignetteCentreX;
  72005. },
  72006. /**
  72007. * Sets Vignette centre X Offset.
  72008. */
  72009. set: function (value) {
  72010. this.imageProcessingConfiguration.vignetteCentreX = value;
  72011. },
  72012. enumerable: true,
  72013. configurable: true
  72014. });
  72015. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  72016. /**
  72017. * Gets Vignette centre Y Offset.
  72018. */
  72019. get: function () {
  72020. return this.imageProcessingConfiguration.vignetteCentreY;
  72021. },
  72022. /**
  72023. * Sets Vignette centre Y Offset.
  72024. */
  72025. set: function (value) {
  72026. this.imageProcessingConfiguration.vignetteCentreY = value;
  72027. },
  72028. enumerable: true,
  72029. configurable: true
  72030. });
  72031. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  72032. /**
  72033. * Gets Vignette weight or intensity of the vignette effect.
  72034. */
  72035. get: function () {
  72036. return this.imageProcessingConfiguration.vignetteWeight;
  72037. },
  72038. /**
  72039. * Sets Vignette weight or intensity of the vignette effect.
  72040. */
  72041. set: function (value) {
  72042. this.imageProcessingConfiguration.vignetteWeight = value;
  72043. },
  72044. enumerable: true,
  72045. configurable: true
  72046. });
  72047. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72048. /**
  72049. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72050. * if vignetteEnabled is set to true.
  72051. */
  72052. get: function () {
  72053. return this.imageProcessingConfiguration.vignetteColor;
  72054. },
  72055. /**
  72056. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72057. * if vignetteEnabled is set to true.
  72058. */
  72059. set: function (value) {
  72060. this.imageProcessingConfiguration.vignetteColor = value;
  72061. },
  72062. enumerable: true,
  72063. configurable: true
  72064. });
  72065. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72066. /**
  72067. * Gets Camera field of view used by the Vignette effect.
  72068. */
  72069. get: function () {
  72070. return this.imageProcessingConfiguration.vignetteCameraFov;
  72071. },
  72072. /**
  72073. * Sets Camera field of view used by the Vignette effect.
  72074. */
  72075. set: function (value) {
  72076. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72077. },
  72078. enumerable: true,
  72079. configurable: true
  72080. });
  72081. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72082. /**
  72083. * Gets the vignette blend mode allowing different kind of effect.
  72084. */
  72085. get: function () {
  72086. return this.imageProcessingConfiguration.vignetteBlendMode;
  72087. },
  72088. /**
  72089. * Sets the vignette blend mode allowing different kind of effect.
  72090. */
  72091. set: function (value) {
  72092. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72093. },
  72094. enumerable: true,
  72095. configurable: true
  72096. });
  72097. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72098. /**
  72099. * Gets wether the vignette effect is enabled.
  72100. */
  72101. get: function () {
  72102. return this.imageProcessingConfiguration.vignetteEnabled;
  72103. },
  72104. /**
  72105. * Sets wether the vignette effect is enabled.
  72106. */
  72107. set: function (value) {
  72108. this.imageProcessingConfiguration.vignetteEnabled = value;
  72109. },
  72110. enumerable: true,
  72111. configurable: true
  72112. });
  72113. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  72114. /**
  72115. * Gets wether the grain effect is enabled.
  72116. */
  72117. get: function () {
  72118. return this.imageProcessingConfiguration.grainEnabled;
  72119. },
  72120. /**
  72121. * Sets wether the grain effect is enabled.
  72122. */
  72123. set: function (value) {
  72124. this.imageProcessingConfiguration.grainEnabled = value;
  72125. },
  72126. enumerable: true,
  72127. configurable: true
  72128. });
  72129. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  72130. /**
  72131. * Gets the grain effect's intensity.
  72132. */
  72133. get: function () {
  72134. return this.imageProcessingConfiguration.grainIntensity;
  72135. },
  72136. /**
  72137. * Sets the grain effect's intensity.
  72138. */
  72139. set: function (value) {
  72140. this.imageProcessingConfiguration.grainIntensity = value;
  72141. },
  72142. enumerable: true,
  72143. configurable: true
  72144. });
  72145. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  72146. /**
  72147. * Gets wether the grain effect is animated.
  72148. */
  72149. get: function () {
  72150. return this.imageProcessingConfiguration.grainAnimated;
  72151. },
  72152. /**
  72153. * Sets wether the grain effect is animated.
  72154. */
  72155. set: function (value) {
  72156. this.imageProcessingConfiguration.grainAnimated = value;
  72157. },
  72158. enumerable: true,
  72159. configurable: true
  72160. });
  72161. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72162. /**
  72163. * Gets wether the input of the processing is in Gamma or Linear Space.
  72164. */
  72165. get: function () {
  72166. return this._fromLinearSpace;
  72167. },
  72168. /**
  72169. * Sets wether the input of the processing is in Gamma or Linear Space.
  72170. */
  72171. set: function (value) {
  72172. if (this._fromLinearSpace === value) {
  72173. return;
  72174. }
  72175. this._fromLinearSpace = value;
  72176. this._updateParameters();
  72177. },
  72178. enumerable: true,
  72179. configurable: true
  72180. });
  72181. ImageProcessingPostProcess.prototype.getClassName = function () {
  72182. return "ImageProcessingPostProcess";
  72183. };
  72184. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72185. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72186. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72187. var defines = "";
  72188. for (var define in this._defines) {
  72189. if (this._defines[define]) {
  72190. defines += "#define " + define + ";\r\n";
  72191. }
  72192. }
  72193. var samplers = ["textureSampler"];
  72194. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72195. var uniforms = ["scale"];
  72196. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72197. this.updateEffect(defines, uniforms, samplers);
  72198. };
  72199. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72200. _super.prototype.dispose.call(this, camera);
  72201. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72202. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72203. }
  72204. this.imageProcessingConfiguration.applyByPostProcess = false;
  72205. };
  72206. __decorate([
  72207. BABYLON.serialize()
  72208. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72209. return ImageProcessingPostProcess;
  72210. }(BABYLON.PostProcess));
  72211. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72212. })(BABYLON || (BABYLON = {}));
  72213. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72214. "use strict";
  72215. var BABYLON;
  72216. (function (BABYLON) {
  72217. var Bone = /** @class */ (function (_super) {
  72218. __extends(Bone, _super);
  72219. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72220. if (parentBone === void 0) { parentBone = null; }
  72221. if (localMatrix === void 0) { localMatrix = null; }
  72222. if (restPose === void 0) { restPose = null; }
  72223. if (baseMatrix === void 0) { baseMatrix = null; }
  72224. if (index === void 0) { index = null; }
  72225. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72226. _this.name = name;
  72227. _this.children = new Array();
  72228. _this.animations = new Array();
  72229. // Set this value to map this bone to a different index in the transform matrices.
  72230. // Set this value to -1 to exclude the bone from the transform matrices.
  72231. _this._index = null;
  72232. _this._worldTransform = new BABYLON.Matrix();
  72233. _this._absoluteTransform = new BABYLON.Matrix();
  72234. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72235. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72236. _this._scaleVector = BABYLON.Vector3.One();
  72237. _this._negateScaleChildren = BABYLON.Vector3.One();
  72238. _this._scalingDeterminant = 1;
  72239. _this._skeleton = skeleton;
  72240. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72241. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72242. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72243. _this._index = index;
  72244. skeleton.bones.push(_this);
  72245. _this.setParent(parentBone, false);
  72246. _this._updateDifferenceMatrix();
  72247. return _this;
  72248. }
  72249. Object.defineProperty(Bone.prototype, "_matrix", {
  72250. get: function () {
  72251. return this._localMatrix;
  72252. },
  72253. set: function (val) {
  72254. if (this._localMatrix) {
  72255. this._localMatrix.copyFrom(val);
  72256. }
  72257. else {
  72258. this._localMatrix = val;
  72259. }
  72260. },
  72261. enumerable: true,
  72262. configurable: true
  72263. });
  72264. // Members
  72265. Bone.prototype.getSkeleton = function () {
  72266. return this._skeleton;
  72267. };
  72268. Bone.prototype.getParent = function () {
  72269. return this._parent;
  72270. };
  72271. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72272. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72273. if (this._parent === parent) {
  72274. return;
  72275. }
  72276. if (this._parent) {
  72277. var index = this._parent.children.indexOf(this);
  72278. if (index !== -1) {
  72279. this._parent.children.splice(index, 1);
  72280. }
  72281. }
  72282. this._parent = parent;
  72283. if (this._parent) {
  72284. this._parent.children.push(this);
  72285. }
  72286. if (updateDifferenceMatrix) {
  72287. this._updateDifferenceMatrix();
  72288. }
  72289. };
  72290. Bone.prototype.getLocalMatrix = function () {
  72291. return this._localMatrix;
  72292. };
  72293. Bone.prototype.getBaseMatrix = function () {
  72294. return this._baseMatrix;
  72295. };
  72296. Bone.prototype.getRestPose = function () {
  72297. return this._restPose;
  72298. };
  72299. Bone.prototype.returnToRest = function () {
  72300. this.updateMatrix(this._restPose.clone());
  72301. };
  72302. Bone.prototype.getWorldMatrix = function () {
  72303. return this._worldTransform;
  72304. };
  72305. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72306. return this._invertedAbsoluteTransform;
  72307. };
  72308. Bone.prototype.getAbsoluteTransform = function () {
  72309. return this._absoluteTransform;
  72310. };
  72311. Object.defineProperty(Bone.prototype, "position", {
  72312. // Properties (matches AbstractMesh properties)
  72313. get: function () {
  72314. return this.getPosition();
  72315. },
  72316. set: function (newPosition) {
  72317. this.setPosition(newPosition);
  72318. },
  72319. enumerable: true,
  72320. configurable: true
  72321. });
  72322. Object.defineProperty(Bone.prototype, "rotation", {
  72323. get: function () {
  72324. return this.getRotation();
  72325. },
  72326. set: function (newRotation) {
  72327. this.setRotation(newRotation);
  72328. },
  72329. enumerable: true,
  72330. configurable: true
  72331. });
  72332. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72333. get: function () {
  72334. return this.getRotationQuaternion();
  72335. },
  72336. set: function (newRotation) {
  72337. this.setRotationQuaternion(newRotation);
  72338. },
  72339. enumerable: true,
  72340. configurable: true
  72341. });
  72342. Object.defineProperty(Bone.prototype, "scaling", {
  72343. get: function () {
  72344. return this.getScale();
  72345. },
  72346. set: function (newScaling) {
  72347. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72348. },
  72349. enumerable: true,
  72350. configurable: true
  72351. });
  72352. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72353. /**
  72354. * Gets the animation properties override
  72355. */
  72356. get: function () {
  72357. return this._skeleton.animationPropertiesOverride;
  72358. },
  72359. enumerable: true,
  72360. configurable: true
  72361. });
  72362. // Methods
  72363. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72364. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72365. this._baseMatrix = matrix.clone();
  72366. this._localMatrix = matrix.clone();
  72367. this._skeleton._markAsDirty();
  72368. if (updateDifferenceMatrix) {
  72369. this._updateDifferenceMatrix();
  72370. }
  72371. };
  72372. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72373. if (!rootMatrix) {
  72374. rootMatrix = this._baseMatrix;
  72375. }
  72376. if (this._parent) {
  72377. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72378. }
  72379. else {
  72380. this._absoluteTransform.copyFrom(rootMatrix);
  72381. }
  72382. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72383. for (var index = 0; index < this.children.length; index++) {
  72384. this.children[index]._updateDifferenceMatrix();
  72385. }
  72386. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72387. };
  72388. Bone.prototype.markAsDirty = function () {
  72389. this._currentRenderId++;
  72390. this._skeleton._markAsDirty();
  72391. };
  72392. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72393. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72394. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72395. // all animation may be coming from a library skeleton, so may need to create animation
  72396. if (this.animations.length === 0) {
  72397. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72398. this.animations[0].setKeys([]);
  72399. }
  72400. // get animation info / verify there is such a range from the source bone
  72401. var sourceRange = source.animations[0].getRange(rangeName);
  72402. if (!sourceRange) {
  72403. return false;
  72404. }
  72405. var from = sourceRange.from;
  72406. var to = sourceRange.to;
  72407. var sourceKeys = source.animations[0].getKeys();
  72408. // rescaling prep
  72409. var sourceBoneLength = source.length;
  72410. var sourceParent = source.getParent();
  72411. var parent = this.getParent();
  72412. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72413. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72414. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72415. var destKeys = this.animations[0].getKeys();
  72416. // loop vars declaration
  72417. var orig;
  72418. var origTranslation;
  72419. var mat;
  72420. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72421. orig = sourceKeys[key];
  72422. if (orig.frame >= from && orig.frame <= to) {
  72423. if (rescaleAsRequired) {
  72424. mat = orig.value.clone();
  72425. // scale based on parent ratio, when bone has parent
  72426. if (parentScalingReqd) {
  72427. origTranslation = mat.getTranslation();
  72428. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72429. // scale based on skeleton dimension ratio when root bone, and value is passed
  72430. }
  72431. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72432. origTranslation = mat.getTranslation();
  72433. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72434. // use original when root bone, and no data for skelDimensionsRatio
  72435. }
  72436. else {
  72437. mat = orig.value;
  72438. }
  72439. }
  72440. else {
  72441. mat = orig.value;
  72442. }
  72443. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72444. }
  72445. }
  72446. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72447. return true;
  72448. };
  72449. /**
  72450. * Translate the bone in local or world space.
  72451. * @param vec The amount to translate the bone.
  72452. * @param space The space that the translation is in.
  72453. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72454. */
  72455. Bone.prototype.translate = function (vec, space, mesh) {
  72456. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72457. var lm = this.getLocalMatrix();
  72458. if (space == BABYLON.Space.LOCAL) {
  72459. lm.m[12] += vec.x;
  72460. lm.m[13] += vec.y;
  72461. lm.m[14] += vec.z;
  72462. }
  72463. else {
  72464. var wm = null;
  72465. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72466. if (mesh) {
  72467. wm = mesh.getWorldMatrix();
  72468. }
  72469. this._skeleton.computeAbsoluteTransforms();
  72470. var tmat = Bone._tmpMats[0];
  72471. var tvec = Bone._tmpVecs[0];
  72472. if (this._parent) {
  72473. if (mesh && wm) {
  72474. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72475. tmat.multiplyToRef(wm, tmat);
  72476. }
  72477. else {
  72478. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72479. }
  72480. }
  72481. tmat.m[12] = 0;
  72482. tmat.m[13] = 0;
  72483. tmat.m[14] = 0;
  72484. tmat.invert();
  72485. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72486. lm.m[12] += tvec.x;
  72487. lm.m[13] += tvec.y;
  72488. lm.m[14] += tvec.z;
  72489. }
  72490. this.markAsDirty();
  72491. };
  72492. /**
  72493. * Set the postion of the bone in local or world space.
  72494. * @param position The position to set the bone.
  72495. * @param space The space that the position is in.
  72496. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72497. */
  72498. Bone.prototype.setPosition = function (position, space, mesh) {
  72499. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72500. var lm = this.getLocalMatrix();
  72501. if (space == BABYLON.Space.LOCAL) {
  72502. lm.m[12] = position.x;
  72503. lm.m[13] = position.y;
  72504. lm.m[14] = position.z;
  72505. }
  72506. else {
  72507. var wm = null;
  72508. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72509. if (mesh) {
  72510. wm = mesh.getWorldMatrix();
  72511. }
  72512. this._skeleton.computeAbsoluteTransforms();
  72513. var tmat = Bone._tmpMats[0];
  72514. var vec = Bone._tmpVecs[0];
  72515. if (this._parent) {
  72516. if (mesh && wm) {
  72517. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72518. tmat.multiplyToRef(wm, tmat);
  72519. }
  72520. else {
  72521. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72522. }
  72523. }
  72524. tmat.invert();
  72525. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72526. lm.m[12] = vec.x;
  72527. lm.m[13] = vec.y;
  72528. lm.m[14] = vec.z;
  72529. }
  72530. this.markAsDirty();
  72531. };
  72532. /**
  72533. * Set the absolute postion of the bone (world space).
  72534. * @param position The position to set the bone.
  72535. * @param mesh The mesh that this bone is attached to.
  72536. */
  72537. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72538. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72539. };
  72540. /**
  72541. * Set the scale of the bone on the x, y and z axes.
  72542. * @param x The scale of the bone on the x axis.
  72543. * @param x The scale of the bone on the y axis.
  72544. * @param z The scale of the bone on the z axis.
  72545. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72546. */
  72547. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72548. if (scaleChildren === void 0) { scaleChildren = false; }
  72549. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72550. if (!scaleChildren) {
  72551. this._negateScaleChildren.x = 1 / x;
  72552. this._negateScaleChildren.y = 1 / y;
  72553. this._negateScaleChildren.z = 1 / z;
  72554. }
  72555. this._syncScaleVector();
  72556. }
  72557. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  72558. };
  72559. /**
  72560. * Scale the bone on the x, y and z axes.
  72561. * @param x The amount to scale the bone on the x axis.
  72562. * @param x The amount to scale the bone on the y axis.
  72563. * @param z The amount to scale the bone on the z axis.
  72564. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72565. */
  72566. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  72567. if (scaleChildren === void 0) { scaleChildren = false; }
  72568. var locMat = this.getLocalMatrix();
  72569. var origLocMat = Bone._tmpMats[0];
  72570. origLocMat.copyFrom(locMat);
  72571. var origLocMatInv = Bone._tmpMats[1];
  72572. origLocMatInv.copyFrom(origLocMat);
  72573. origLocMatInv.invert();
  72574. var scaleMat = Bone._tmpMats[2];
  72575. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  72576. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  72577. this._scaleVector.x *= x;
  72578. this._scaleVector.y *= y;
  72579. this._scaleVector.z *= z;
  72580. locMat.multiplyToRef(origLocMatInv, locMat);
  72581. locMat.multiplyToRef(scaleMat, locMat);
  72582. locMat.multiplyToRef(origLocMat, locMat);
  72583. var parent = this.getParent();
  72584. if (parent) {
  72585. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  72586. }
  72587. else {
  72588. this.getAbsoluteTransform().copyFrom(locMat);
  72589. }
  72590. var len = this.children.length;
  72591. scaleMat.invert();
  72592. for (var i = 0; i < len; i++) {
  72593. var child = this.children[i];
  72594. var cm = child.getLocalMatrix();
  72595. cm.multiplyToRef(scaleMat, cm);
  72596. var lm = child.getLocalMatrix();
  72597. lm.m[12] *= x;
  72598. lm.m[13] *= y;
  72599. lm.m[14] *= z;
  72600. }
  72601. this.computeAbsoluteTransforms();
  72602. if (scaleChildren) {
  72603. for (var i = 0; i < len; i++) {
  72604. this.children[i].scale(x, y, z, scaleChildren);
  72605. }
  72606. }
  72607. this.markAsDirty();
  72608. };
  72609. /**
  72610. * Set the yaw, pitch, and roll of the bone in local or world space.
  72611. * @param yaw The rotation of the bone on the y axis.
  72612. * @param pitch The rotation of the bone on the x axis.
  72613. * @param roll The rotation of the bone on the z axis.
  72614. * @param space The space that the axes of rotation are in.
  72615. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72616. */
  72617. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  72618. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72619. var rotMat = Bone._tmpMats[0];
  72620. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72621. var rotMatInv = Bone._tmpMats[1];
  72622. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72623. rotMatInv.multiplyToRef(rotMat, rotMat);
  72624. this._rotateWithMatrix(rotMat, space, mesh);
  72625. };
  72626. /**
  72627. * Rotate the bone on an axis in local or world space.
  72628. * @param axis The axis to rotate the bone on.
  72629. * @param amount The amount to rotate the bone.
  72630. * @param space The space that the axis is in.
  72631. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72632. */
  72633. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72634. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72635. var rmat = Bone._tmpMats[0];
  72636. rmat.m[12] = 0;
  72637. rmat.m[13] = 0;
  72638. rmat.m[14] = 0;
  72639. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72640. this._rotateWithMatrix(rmat, space, mesh);
  72641. };
  72642. /**
  72643. * Set the rotation of the bone to a particular axis angle in local or world space.
  72644. * @param axis The axis to rotate the bone on.
  72645. * @param angle The angle that the bone should be rotated to.
  72646. * @param space The space that the axis is in.
  72647. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72648. */
  72649. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  72650. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72651. var rotMat = Bone._tmpMats[0];
  72652. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  72653. var rotMatInv = Bone._tmpMats[1];
  72654. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72655. rotMatInv.multiplyToRef(rotMat, rotMat);
  72656. this._rotateWithMatrix(rotMat, space, mesh);
  72657. };
  72658. /**
  72659. * Set the euler rotation of the bone in local of world space.
  72660. * @param rotation The euler rotation that the bone should be set to.
  72661. * @param space The space that the rotation is in.
  72662. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72663. */
  72664. Bone.prototype.setRotation = function (rotation, space, mesh) {
  72665. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72666. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  72667. };
  72668. /**
  72669. * Set the quaternion rotation of the bone in local of world space.
  72670. * @param quat The quaternion rotation that the bone should be set to.
  72671. * @param space The space that the rotation is in.
  72672. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72673. */
  72674. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  72675. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72676. var rotMatInv = Bone._tmpMats[0];
  72677. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72678. var rotMat = Bone._tmpMats[1];
  72679. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  72680. rotMatInv.multiplyToRef(rotMat, rotMat);
  72681. this._rotateWithMatrix(rotMat, space, mesh);
  72682. };
  72683. /**
  72684. * Set the rotation matrix of the bone in local of world space.
  72685. * @param rotMat The rotation matrix that the bone should be set to.
  72686. * @param space The space that the rotation is in.
  72687. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72688. */
  72689. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  72690. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72691. var rotMatInv = Bone._tmpMats[0];
  72692. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72693. var rotMat2 = Bone._tmpMats[1];
  72694. rotMat2.copyFrom(rotMat);
  72695. rotMatInv.multiplyToRef(rotMat, rotMat2);
  72696. this._rotateWithMatrix(rotMat2, space, mesh);
  72697. };
  72698. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  72699. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72700. var lmat = this.getLocalMatrix();
  72701. var lx = lmat.m[12];
  72702. var ly = lmat.m[13];
  72703. var lz = lmat.m[14];
  72704. var parent = this.getParent();
  72705. var parentScale = Bone._tmpMats[3];
  72706. var parentScaleInv = Bone._tmpMats[4];
  72707. if (parent) {
  72708. if (space == BABYLON.Space.WORLD) {
  72709. if (mesh) {
  72710. parentScale.copyFrom(mesh.getWorldMatrix());
  72711. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  72712. }
  72713. else {
  72714. parentScale.copyFrom(parent.getAbsoluteTransform());
  72715. }
  72716. }
  72717. else {
  72718. parentScale = parent._scaleMatrix;
  72719. }
  72720. parentScaleInv.copyFrom(parentScale);
  72721. parentScaleInv.invert();
  72722. lmat.multiplyToRef(parentScale, lmat);
  72723. lmat.multiplyToRef(rmat, lmat);
  72724. lmat.multiplyToRef(parentScaleInv, lmat);
  72725. }
  72726. else {
  72727. if (space == BABYLON.Space.WORLD && mesh) {
  72728. parentScale.copyFrom(mesh.getWorldMatrix());
  72729. parentScaleInv.copyFrom(parentScale);
  72730. parentScaleInv.invert();
  72731. lmat.multiplyToRef(parentScale, lmat);
  72732. lmat.multiplyToRef(rmat, lmat);
  72733. lmat.multiplyToRef(parentScaleInv, lmat);
  72734. }
  72735. else {
  72736. lmat.multiplyToRef(rmat, lmat);
  72737. }
  72738. }
  72739. lmat.m[12] = lx;
  72740. lmat.m[13] = ly;
  72741. lmat.m[14] = lz;
  72742. this.computeAbsoluteTransforms();
  72743. this.markAsDirty();
  72744. };
  72745. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  72746. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72747. if (space == BABYLON.Space.WORLD) {
  72748. var scaleMatrix = Bone._tmpMats[2];
  72749. scaleMatrix.copyFrom(this._scaleMatrix);
  72750. rotMatInv.copyFrom(this.getAbsoluteTransform());
  72751. if (mesh) {
  72752. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  72753. var meshScale = Bone._tmpMats[3];
  72754. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  72755. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  72756. }
  72757. rotMatInv.invert();
  72758. scaleMatrix.m[0] *= this._scalingDeterminant;
  72759. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72760. }
  72761. else {
  72762. rotMatInv.copyFrom(this.getLocalMatrix());
  72763. rotMatInv.invert();
  72764. var scaleMatrix = Bone._tmpMats[2];
  72765. scaleMatrix.copyFrom(this._scaleMatrix);
  72766. if (this._parent) {
  72767. var pscaleMatrix = Bone._tmpMats[3];
  72768. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  72769. pscaleMatrix.invert();
  72770. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  72771. }
  72772. else {
  72773. scaleMatrix.m[0] *= this._scalingDeterminant;
  72774. }
  72775. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72776. }
  72777. };
  72778. /**
  72779. * Get the scale of the bone
  72780. * @returns the scale of the bone
  72781. */
  72782. Bone.prototype.getScale = function () {
  72783. return this._scaleVector.clone();
  72784. };
  72785. /**
  72786. * Copy the scale of the bone to a vector3.
  72787. * @param result The vector3 to copy the scale to
  72788. */
  72789. Bone.prototype.getScaleToRef = function (result) {
  72790. result.copyFrom(this._scaleVector);
  72791. };
  72792. /**
  72793. * Get the position of the bone in local or world space.
  72794. * @param space The space that the returned position is in.
  72795. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72796. * @returns The position of the bone
  72797. */
  72798. Bone.prototype.getPosition = function (space, mesh) {
  72799. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72800. if (mesh === void 0) { mesh = null; }
  72801. var pos = BABYLON.Vector3.Zero();
  72802. this.getPositionToRef(space, mesh, pos);
  72803. return pos;
  72804. };
  72805. /**
  72806. * Copy the position of the bone to a vector3 in local or world space.
  72807. * @param space The space that the returned position is in.
  72808. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72809. * @param result The vector3 to copy the position to.
  72810. */
  72811. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  72812. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72813. if (space == BABYLON.Space.LOCAL) {
  72814. var lm = this.getLocalMatrix();
  72815. result.x = lm.m[12];
  72816. result.y = lm.m[13];
  72817. result.z = lm.m[14];
  72818. }
  72819. else {
  72820. var wm = null;
  72821. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72822. if (mesh) {
  72823. wm = mesh.getWorldMatrix();
  72824. }
  72825. this._skeleton.computeAbsoluteTransforms();
  72826. var tmat = Bone._tmpMats[0];
  72827. if (mesh && wm) {
  72828. tmat.copyFrom(this.getAbsoluteTransform());
  72829. tmat.multiplyToRef(wm, tmat);
  72830. }
  72831. else {
  72832. tmat = this.getAbsoluteTransform();
  72833. }
  72834. result.x = tmat.m[12];
  72835. result.y = tmat.m[13];
  72836. result.z = tmat.m[14];
  72837. }
  72838. };
  72839. /**
  72840. * Get the absolute position of the bone (world space).
  72841. * @param mesh The mesh that this bone is attached to.
  72842. * @returns The absolute position of the bone
  72843. */
  72844. Bone.prototype.getAbsolutePosition = function (mesh) {
  72845. if (mesh === void 0) { mesh = null; }
  72846. var pos = BABYLON.Vector3.Zero();
  72847. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  72848. return pos;
  72849. };
  72850. /**
  72851. * Copy the absolute position of the bone (world space) to the result param.
  72852. * @param mesh The mesh that this bone is attached to.
  72853. * @param result The vector3 to copy the absolute position to.
  72854. */
  72855. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  72856. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  72857. };
  72858. /**
  72859. * Compute the absolute transforms of this bone and its children.
  72860. */
  72861. Bone.prototype.computeAbsoluteTransforms = function () {
  72862. if (this._parent) {
  72863. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72864. }
  72865. else {
  72866. this._absoluteTransform.copyFrom(this._localMatrix);
  72867. var poseMatrix = this._skeleton.getPoseMatrix();
  72868. if (poseMatrix) {
  72869. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  72870. }
  72871. }
  72872. var children = this.children;
  72873. var len = children.length;
  72874. for (var i = 0; i < len; i++) {
  72875. children[i].computeAbsoluteTransforms();
  72876. }
  72877. };
  72878. Bone.prototype._syncScaleVector = function () {
  72879. var lm = this.getLocalMatrix();
  72880. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  72881. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  72882. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  72883. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  72884. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  72885. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  72886. this._scaleVector.x = xs * Math.sqrt(xsq);
  72887. this._scaleVector.y = ys * Math.sqrt(ysq);
  72888. this._scaleVector.z = zs * Math.sqrt(zsq);
  72889. if (this._parent) {
  72890. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  72891. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  72892. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  72893. }
  72894. 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);
  72895. };
  72896. /**
  72897. * Get the world direction from an axis that is in the local space of the bone.
  72898. * @param localAxis The local direction that is used to compute the world direction.
  72899. * @param mesh The mesh that this bone is attached to.
  72900. * @returns The world direction
  72901. */
  72902. Bone.prototype.getDirection = function (localAxis, mesh) {
  72903. if (mesh === void 0) { mesh = null; }
  72904. var result = BABYLON.Vector3.Zero();
  72905. this.getDirectionToRef(localAxis, mesh, result);
  72906. return result;
  72907. };
  72908. /**
  72909. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72910. * @param localAxis The local direction that is used to compute the world direction.
  72911. * @param mesh The mesh that this bone is attached to.
  72912. * @param result The vector3 that the world direction will be copied to.
  72913. */
  72914. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72915. if (mesh === void 0) { mesh = null; }
  72916. var wm = null;
  72917. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72918. if (mesh) {
  72919. wm = mesh.getWorldMatrix();
  72920. }
  72921. this._skeleton.computeAbsoluteTransforms();
  72922. var mat = Bone._tmpMats[0];
  72923. mat.copyFrom(this.getAbsoluteTransform());
  72924. if (mesh && wm) {
  72925. mat.multiplyToRef(wm, mat);
  72926. }
  72927. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72928. result.normalize();
  72929. };
  72930. /**
  72931. * Get the euler rotation of the bone in local or world space.
  72932. * @param space The space that the rotation should be in.
  72933. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72934. * @returns The euler rotation
  72935. */
  72936. Bone.prototype.getRotation = function (space, mesh) {
  72937. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72938. if (mesh === void 0) { mesh = null; }
  72939. var result = BABYLON.Vector3.Zero();
  72940. this.getRotationToRef(space, mesh, result);
  72941. return result;
  72942. };
  72943. /**
  72944. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72945. * @param space The space that the rotation should be in.
  72946. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72947. * @param result The vector3 that the rotation should be copied to.
  72948. */
  72949. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72950. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72951. if (mesh === void 0) { mesh = null; }
  72952. var quat = Bone._tmpQuat;
  72953. this.getRotationQuaternionToRef(space, mesh, quat);
  72954. quat.toEulerAnglesToRef(result);
  72955. };
  72956. /**
  72957. * Get the quaternion rotation of the bone in either local or world space.
  72958. * @param space The space that the rotation should be in.
  72959. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72960. * @returns The quaternion rotation
  72961. */
  72962. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72963. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72964. if (mesh === void 0) { mesh = null; }
  72965. var result = BABYLON.Quaternion.Identity();
  72966. this.getRotationQuaternionToRef(space, mesh, result);
  72967. return result;
  72968. };
  72969. /**
  72970. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72971. * @param space The space that the rotation should be in.
  72972. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72973. * @param result The quaternion that the rotation should be copied to.
  72974. */
  72975. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72976. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72977. if (mesh === void 0) { mesh = null; }
  72978. if (space == BABYLON.Space.LOCAL) {
  72979. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72980. }
  72981. else {
  72982. var mat = Bone._tmpMats[0];
  72983. var amat = this.getAbsoluteTransform();
  72984. if (mesh) {
  72985. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72986. }
  72987. else {
  72988. mat.copyFrom(amat);
  72989. }
  72990. mat.m[0] *= this._scalingDeterminant;
  72991. mat.m[1] *= this._scalingDeterminant;
  72992. mat.m[2] *= this._scalingDeterminant;
  72993. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72994. }
  72995. };
  72996. /**
  72997. * Get the rotation matrix of the bone in local or world space.
  72998. * @param space The space that the rotation should be in.
  72999. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73000. * @returns The rotation matrix
  73001. */
  73002. Bone.prototype.getRotationMatrix = function (space, mesh) {
  73003. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73004. var result = BABYLON.Matrix.Identity();
  73005. this.getRotationMatrixToRef(space, mesh, result);
  73006. return result;
  73007. };
  73008. /**
  73009. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  73010. * @param space The space that the rotation should be in.
  73011. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73012. * @param result The quaternion that the rotation should be copied to.
  73013. */
  73014. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  73015. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73016. if (space == BABYLON.Space.LOCAL) {
  73017. this.getLocalMatrix().getRotationMatrixToRef(result);
  73018. }
  73019. else {
  73020. var mat = Bone._tmpMats[0];
  73021. var amat = this.getAbsoluteTransform();
  73022. if (mesh) {
  73023. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73024. }
  73025. else {
  73026. mat.copyFrom(amat);
  73027. }
  73028. mat.m[0] *= this._scalingDeterminant;
  73029. mat.m[1] *= this._scalingDeterminant;
  73030. mat.m[2] *= this._scalingDeterminant;
  73031. mat.getRotationMatrixToRef(result);
  73032. }
  73033. };
  73034. /**
  73035. * Get the world position of a point that is in the local space of the bone.
  73036. * @param position The local position
  73037. * @param mesh The mesh that this bone is attached to.
  73038. * @returns The world position
  73039. */
  73040. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  73041. if (mesh === void 0) { mesh = null; }
  73042. var result = BABYLON.Vector3.Zero();
  73043. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  73044. return result;
  73045. };
  73046. /**
  73047. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73048. * @param position The local position
  73049. * @param mesh The mesh that this bone is attached to.
  73050. * @param result The vector3 that the world position should be copied to.
  73051. */
  73052. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73053. if (mesh === void 0) { mesh = null; }
  73054. var wm = null;
  73055. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73056. if (mesh) {
  73057. wm = mesh.getWorldMatrix();
  73058. }
  73059. this._skeleton.computeAbsoluteTransforms();
  73060. var tmat = Bone._tmpMats[0];
  73061. if (mesh && wm) {
  73062. tmat.copyFrom(this.getAbsoluteTransform());
  73063. tmat.multiplyToRef(wm, tmat);
  73064. }
  73065. else {
  73066. tmat = this.getAbsoluteTransform();
  73067. }
  73068. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73069. };
  73070. /**
  73071. * Get the local position of a point that is in world space.
  73072. * @param position The world position
  73073. * @param mesh The mesh that this bone is attached to.
  73074. * @returns The local position
  73075. */
  73076. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73077. if (mesh === void 0) { mesh = null; }
  73078. var result = BABYLON.Vector3.Zero();
  73079. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73080. return result;
  73081. };
  73082. /**
  73083. * Get the local position of a point that is in world space and copy it to the result param.
  73084. * @param position The world position
  73085. * @param mesh The mesh that this bone is attached to.
  73086. * @param result The vector3 that the local position should be copied to.
  73087. */
  73088. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73089. if (mesh === void 0) { mesh = null; }
  73090. var wm = null;
  73091. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73092. if (mesh) {
  73093. wm = mesh.getWorldMatrix();
  73094. }
  73095. this._skeleton.computeAbsoluteTransforms();
  73096. var tmat = Bone._tmpMats[0];
  73097. tmat.copyFrom(this.getAbsoluteTransform());
  73098. if (mesh && wm) {
  73099. tmat.multiplyToRef(wm, tmat);
  73100. }
  73101. tmat.invert();
  73102. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73103. };
  73104. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73105. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73106. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73107. return Bone;
  73108. }(BABYLON.Node));
  73109. BABYLON.Bone = Bone;
  73110. })(BABYLON || (BABYLON = {}));
  73111. //# sourceMappingURL=babylon.bone.js.map
  73112. "use strict";
  73113. var BABYLON;
  73114. (function (BABYLON) {
  73115. var BoneIKController = /** @class */ (function () {
  73116. function BoneIKController(mesh, bone, options) {
  73117. this.targetPosition = BABYLON.Vector3.Zero();
  73118. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73119. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73120. this.poleAngle = 0;
  73121. this.slerpAmount = 1;
  73122. this._bone1Quat = BABYLON.Quaternion.Identity();
  73123. this._bone1Mat = BABYLON.Matrix.Identity();
  73124. this._bone2Ang = Math.PI;
  73125. this._maxAngle = Math.PI;
  73126. this._rightHandedSystem = false;
  73127. this._bendAxis = BABYLON.Vector3.Right();
  73128. this._slerping = false;
  73129. this._adjustRoll = 0;
  73130. this._bone2 = bone;
  73131. this._bone1 = bone.getParent();
  73132. if (!this._bone1) {
  73133. return;
  73134. }
  73135. this.mesh = mesh;
  73136. var bonePos = bone.getPosition();
  73137. if (bone.getAbsoluteTransform().determinant() > 0) {
  73138. this._rightHandedSystem = true;
  73139. this._bendAxis.x = 0;
  73140. this._bendAxis.y = 0;
  73141. this._bendAxis.z = -1;
  73142. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73143. this._adjustRoll = Math.PI * .5;
  73144. this._bendAxis.z = 1;
  73145. }
  73146. }
  73147. if (this._bone1.length) {
  73148. var boneScale1 = this._bone1.getScale();
  73149. var boneScale2 = this._bone2.getScale();
  73150. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73151. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73152. }
  73153. else if (this._bone1.children[0]) {
  73154. mesh.computeWorldMatrix(true);
  73155. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73156. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73157. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73158. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73159. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73160. }
  73161. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73162. this.maxAngle = Math.PI;
  73163. if (options) {
  73164. if (options.targetMesh) {
  73165. this.targetMesh = options.targetMesh;
  73166. this.targetMesh.computeWorldMatrix(true);
  73167. }
  73168. if (options.poleTargetMesh) {
  73169. this.poleTargetMesh = options.poleTargetMesh;
  73170. this.poleTargetMesh.computeWorldMatrix(true);
  73171. }
  73172. else if (options.poleTargetBone) {
  73173. this.poleTargetBone = options.poleTargetBone;
  73174. }
  73175. else if (this._bone1.getParent()) {
  73176. this.poleTargetBone = this._bone1.getParent();
  73177. }
  73178. if (options.poleTargetLocalOffset) {
  73179. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73180. }
  73181. if (options.poleAngle) {
  73182. this.poleAngle = options.poleAngle;
  73183. }
  73184. if (options.bendAxis) {
  73185. this._bendAxis.copyFrom(options.bendAxis);
  73186. }
  73187. if (options.maxAngle) {
  73188. this.maxAngle = options.maxAngle;
  73189. }
  73190. if (options.slerpAmount) {
  73191. this.slerpAmount = options.slerpAmount;
  73192. }
  73193. }
  73194. }
  73195. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73196. get: function () {
  73197. return this._maxAngle;
  73198. },
  73199. set: function (value) {
  73200. this._setMaxAngle(value);
  73201. },
  73202. enumerable: true,
  73203. configurable: true
  73204. });
  73205. BoneIKController.prototype._setMaxAngle = function (ang) {
  73206. if (ang < 0) {
  73207. ang = 0;
  73208. }
  73209. if (ang > Math.PI || ang == undefined) {
  73210. ang = Math.PI;
  73211. }
  73212. this._maxAngle = ang;
  73213. var a = this._bone1Length;
  73214. var b = this._bone2Length;
  73215. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73216. };
  73217. BoneIKController.prototype.update = function () {
  73218. var bone1 = this._bone1;
  73219. if (!bone1) {
  73220. return;
  73221. }
  73222. var target = this.targetPosition;
  73223. var poleTarget = this.poleTargetPosition;
  73224. var mat1 = BoneIKController._tmpMats[0];
  73225. var mat2 = BoneIKController._tmpMats[1];
  73226. if (this.targetMesh) {
  73227. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73228. }
  73229. if (this.poleTargetBone) {
  73230. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73231. }
  73232. else if (this.poleTargetMesh) {
  73233. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73234. }
  73235. var bonePos = BoneIKController._tmpVecs[0];
  73236. var zaxis = BoneIKController._tmpVecs[1];
  73237. var xaxis = BoneIKController._tmpVecs[2];
  73238. var yaxis = BoneIKController._tmpVecs[3];
  73239. var upAxis = BoneIKController._tmpVecs[4];
  73240. var _tmpQuat = BoneIKController._tmpQuat;
  73241. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73242. poleTarget.subtractToRef(bonePos, upAxis);
  73243. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73244. upAxis.y = 1;
  73245. }
  73246. else {
  73247. upAxis.normalize();
  73248. }
  73249. target.subtractToRef(bonePos, yaxis);
  73250. yaxis.normalize();
  73251. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73252. zaxis.normalize();
  73253. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73254. xaxis.normalize();
  73255. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73256. var a = this._bone1Length;
  73257. var b = this._bone2Length;
  73258. var c = BABYLON.Vector3.Distance(bonePos, target);
  73259. if (this._maxReach > 0) {
  73260. c = Math.min(this._maxReach, c);
  73261. }
  73262. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73263. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73264. if (acosa > 1) {
  73265. acosa = 1;
  73266. }
  73267. if (acosb > 1) {
  73268. acosb = 1;
  73269. }
  73270. if (acosa < -1) {
  73271. acosa = -1;
  73272. }
  73273. if (acosb < -1) {
  73274. acosb = -1;
  73275. }
  73276. var angA = Math.acos(acosa);
  73277. var angB = Math.acos(acosb);
  73278. var angC = -angA - angB;
  73279. if (this._rightHandedSystem) {
  73280. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73281. mat2.multiplyToRef(mat1, mat1);
  73282. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73283. mat2.multiplyToRef(mat1, mat1);
  73284. }
  73285. else {
  73286. var _tmpVec = BoneIKController._tmpVecs[5];
  73287. _tmpVec.copyFrom(this._bendAxis);
  73288. _tmpVec.x *= -1;
  73289. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73290. mat2.multiplyToRef(mat1, mat1);
  73291. }
  73292. if (this.poleAngle) {
  73293. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73294. mat1.multiplyToRef(mat2, mat1);
  73295. }
  73296. if (this._bone1) {
  73297. if (this.slerpAmount < 1) {
  73298. if (!this._slerping) {
  73299. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73300. }
  73301. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73302. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73303. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73304. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73305. this._slerping = true;
  73306. }
  73307. else {
  73308. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73309. this._bone1Mat.copyFrom(mat1);
  73310. this._slerping = false;
  73311. }
  73312. }
  73313. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73314. this._bone2Ang = angC;
  73315. };
  73316. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73317. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73318. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73319. return BoneIKController;
  73320. }());
  73321. BABYLON.BoneIKController = BoneIKController;
  73322. })(BABYLON || (BABYLON = {}));
  73323. //# sourceMappingURL=babylon.boneIKController.js.map
  73324. "use strict";
  73325. var BABYLON;
  73326. (function (BABYLON) {
  73327. var BoneLookController = /** @class */ (function () {
  73328. /**
  73329. * Create a BoneLookController
  73330. * @param mesh the mesh that the bone belongs to
  73331. * @param bone the bone that will be looking to the target
  73332. * @param target the target Vector3 to look at
  73333. * @param settings optional settings:
  73334. * - maxYaw: the maximum angle the bone will yaw to
  73335. * - minYaw: the minimum angle the bone will yaw to
  73336. * - maxPitch: the maximum angle the bone will pitch to
  73337. * - minPitch: the minimum angle the bone will yaw to
  73338. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73339. * - upAxis: the up axis of the coordinate system
  73340. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73341. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73342. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73343. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73344. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73345. * - adjustRoll: used to make an adjustment to the roll of the bone
  73346. **/
  73347. function BoneLookController(mesh, bone, target, options) {
  73348. /**
  73349. * The up axis of the coordinate system that is used when the bone is rotated.
  73350. */
  73351. this.upAxis = BABYLON.Vector3.Up();
  73352. /**
  73353. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73354. */
  73355. this.upAxisSpace = BABYLON.Space.LOCAL;
  73356. /**
  73357. * Used to make an adjustment to the yaw of the bone.
  73358. */
  73359. this.adjustYaw = 0;
  73360. /**
  73361. * Used to make an adjustment to the pitch of the bone.
  73362. */
  73363. this.adjustPitch = 0;
  73364. /**
  73365. * Used to make an adjustment to the roll of the bone.
  73366. */
  73367. this.adjustRoll = 0;
  73368. /**
  73369. * 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).
  73370. */
  73371. this.slerpAmount = 1;
  73372. this._boneQuat = BABYLON.Quaternion.Identity();
  73373. this._slerping = false;
  73374. this._firstFrameSkipped = false;
  73375. this._fowardAxis = BABYLON.Vector3.Forward();
  73376. this.mesh = mesh;
  73377. this.bone = bone;
  73378. this.target = target;
  73379. if (options) {
  73380. if (options.adjustYaw) {
  73381. this.adjustYaw = options.adjustYaw;
  73382. }
  73383. if (options.adjustPitch) {
  73384. this.adjustPitch = options.adjustPitch;
  73385. }
  73386. if (options.adjustRoll) {
  73387. this.adjustRoll = options.adjustRoll;
  73388. }
  73389. if (options.maxYaw != null) {
  73390. this.maxYaw = options.maxYaw;
  73391. }
  73392. else {
  73393. this.maxYaw = Math.PI;
  73394. }
  73395. if (options.minYaw != null) {
  73396. this.minYaw = options.minYaw;
  73397. }
  73398. else {
  73399. this.minYaw = -Math.PI;
  73400. }
  73401. if (options.maxPitch != null) {
  73402. this.maxPitch = options.maxPitch;
  73403. }
  73404. else {
  73405. this.maxPitch = Math.PI;
  73406. }
  73407. if (options.minPitch != null) {
  73408. this.minPitch = options.minPitch;
  73409. }
  73410. else {
  73411. this.minPitch = -Math.PI;
  73412. }
  73413. if (options.slerpAmount != null) {
  73414. this.slerpAmount = options.slerpAmount;
  73415. }
  73416. if (options.upAxis != null) {
  73417. this.upAxis = options.upAxis;
  73418. }
  73419. if (options.upAxisSpace != null) {
  73420. this.upAxisSpace = options.upAxisSpace;
  73421. }
  73422. if (options.yawAxis != null || options.pitchAxis != null) {
  73423. var newYawAxis = BABYLON.Axis.Y;
  73424. var newPitchAxis = BABYLON.Axis.X;
  73425. if (options.yawAxis != null) {
  73426. newYawAxis = options.yawAxis.clone();
  73427. newYawAxis.normalize();
  73428. }
  73429. if (options.pitchAxis != null) {
  73430. newPitchAxis = options.pitchAxis.clone();
  73431. newPitchAxis.normalize();
  73432. }
  73433. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73434. this._transformYawPitch = BABYLON.Matrix.Identity();
  73435. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73436. this._transformYawPitchInv = this._transformYawPitch.clone();
  73437. this._transformYawPitch.invert();
  73438. }
  73439. }
  73440. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73441. this.upAxisSpace = BABYLON.Space.LOCAL;
  73442. }
  73443. }
  73444. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73445. /**
  73446. * Get/set the minimum yaw angle that the bone can look to.
  73447. */
  73448. get: function () {
  73449. return this._minYaw;
  73450. },
  73451. set: function (value) {
  73452. this._minYaw = value;
  73453. this._minYawSin = Math.sin(value);
  73454. this._minYawCos = Math.cos(value);
  73455. if (this._maxYaw != null) {
  73456. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73457. this._yawRange = this._maxYaw - this._minYaw;
  73458. }
  73459. },
  73460. enumerable: true,
  73461. configurable: true
  73462. });
  73463. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73464. /**
  73465. * Get/set the maximum yaw angle that the bone can look to.
  73466. */
  73467. get: function () {
  73468. return this._maxYaw;
  73469. },
  73470. set: function (value) {
  73471. this._maxYaw = value;
  73472. this._maxYawSin = Math.sin(value);
  73473. this._maxYawCos = Math.cos(value);
  73474. if (this._minYaw != null) {
  73475. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73476. this._yawRange = this._maxYaw - this._minYaw;
  73477. }
  73478. },
  73479. enumerable: true,
  73480. configurable: true
  73481. });
  73482. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73483. /**
  73484. * Get/set the minimum pitch angle that the bone can look to.
  73485. */
  73486. get: function () {
  73487. return this._minPitch;
  73488. },
  73489. set: function (value) {
  73490. this._minPitch = value;
  73491. this._minPitchTan = Math.tan(value);
  73492. },
  73493. enumerable: true,
  73494. configurable: true
  73495. });
  73496. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73497. /**
  73498. * Get/set the maximum pitch angle that the bone can look to.
  73499. */
  73500. get: function () {
  73501. return this._maxPitch;
  73502. },
  73503. set: function (value) {
  73504. this._maxPitch = value;
  73505. this._maxPitchTan = Math.tan(value);
  73506. },
  73507. enumerable: true,
  73508. configurable: true
  73509. });
  73510. /**
  73511. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73512. */
  73513. BoneLookController.prototype.update = function () {
  73514. //skip the first frame when slerping so that the mesh rotation is correct
  73515. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73516. this._firstFrameSkipped = true;
  73517. return;
  73518. }
  73519. var bone = this.bone;
  73520. var bonePos = BoneLookController._tmpVecs[0];
  73521. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73522. var target = this.target;
  73523. var _tmpMat1 = BoneLookController._tmpMats[0];
  73524. var _tmpMat2 = BoneLookController._tmpMats[1];
  73525. var mesh = this.mesh;
  73526. var parentBone = bone.getParent();
  73527. var upAxis = BoneLookController._tmpVecs[1];
  73528. upAxis.copyFrom(this.upAxis);
  73529. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73530. if (this._transformYawPitch) {
  73531. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73532. }
  73533. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73534. }
  73535. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73536. mesh.getDirectionToRef(upAxis, upAxis);
  73537. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73538. upAxis.normalize();
  73539. }
  73540. }
  73541. var checkYaw = false;
  73542. var checkPitch = false;
  73543. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73544. checkYaw = true;
  73545. }
  73546. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73547. checkPitch = true;
  73548. }
  73549. if (checkYaw || checkPitch) {
  73550. var spaceMat = BoneLookController._tmpMats[2];
  73551. var spaceMatInv = BoneLookController._tmpMats[3];
  73552. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  73553. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  73554. }
  73555. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  73556. spaceMat.copyFrom(mesh.getWorldMatrix());
  73557. }
  73558. else {
  73559. var forwardAxis = BoneLookController._tmpVecs[2];
  73560. forwardAxis.copyFrom(this._fowardAxis);
  73561. if (this._transformYawPitch) {
  73562. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  73563. }
  73564. if (parentBone) {
  73565. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  73566. }
  73567. else {
  73568. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  73569. }
  73570. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  73571. rightAxis.normalize();
  73572. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  73573. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  73574. }
  73575. spaceMat.invertToRef(spaceMatInv);
  73576. var xzlen = null;
  73577. if (checkPitch) {
  73578. var localTarget = BoneLookController._tmpVecs[3];
  73579. target.subtractToRef(bonePos, localTarget);
  73580. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73581. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73582. var pitch = Math.atan2(localTarget.y, xzlen);
  73583. var newPitch = pitch;
  73584. if (pitch > this._maxPitch) {
  73585. localTarget.y = this._maxPitchTan * xzlen;
  73586. newPitch = this._maxPitch;
  73587. }
  73588. else if (pitch < this._minPitch) {
  73589. localTarget.y = this._minPitchTan * xzlen;
  73590. newPitch = this._minPitch;
  73591. }
  73592. if (pitch != newPitch) {
  73593. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73594. localTarget.addInPlace(bonePos);
  73595. target = localTarget;
  73596. }
  73597. }
  73598. if (checkYaw) {
  73599. var localTarget = BoneLookController._tmpVecs[4];
  73600. target.subtractToRef(bonePos, localTarget);
  73601. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73602. var yaw = Math.atan2(localTarget.x, localTarget.z);
  73603. var newYaw = yaw;
  73604. if (yaw > this._maxYaw || yaw < this._minYaw) {
  73605. if (xzlen == null) {
  73606. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73607. }
  73608. if (this._yawRange > Math.PI) {
  73609. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  73610. localTarget.z = this._maxYawCos * xzlen;
  73611. localTarget.x = this._maxYawSin * xzlen;
  73612. newYaw = this._maxYaw;
  73613. }
  73614. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  73615. localTarget.z = this._minYawCos * xzlen;
  73616. localTarget.x = this._minYawSin * xzlen;
  73617. newYaw = this._minYaw;
  73618. }
  73619. }
  73620. else {
  73621. if (yaw > this._maxYaw) {
  73622. localTarget.z = this._maxYawCos * xzlen;
  73623. localTarget.x = this._maxYawSin * xzlen;
  73624. newYaw = this._maxYaw;
  73625. }
  73626. else if (yaw < this._minYaw) {
  73627. localTarget.z = this._minYawCos * xzlen;
  73628. localTarget.x = this._minYawSin * xzlen;
  73629. newYaw = this._minYaw;
  73630. }
  73631. }
  73632. }
  73633. if (this._slerping && this._yawRange > Math.PI) {
  73634. //are we going to be crossing into the min/max region?
  73635. var boneFwd = BoneLookController._tmpVecs[8];
  73636. boneFwd.copyFrom(BABYLON.Axis.Z);
  73637. if (this._transformYawPitch) {
  73638. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73639. }
  73640. var boneRotMat = BoneLookController._tmpMats[4];
  73641. this._boneQuat.toRotationMatrix(boneRotMat);
  73642. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73643. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73644. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73645. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73646. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73647. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  73648. if (angBtwTar > angBtwMidYaw) {
  73649. if (xzlen == null) {
  73650. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73651. }
  73652. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  73653. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  73654. if (angBtwMin < angBtwMax) {
  73655. newYaw = boneYaw + Math.PI * .75;
  73656. localTarget.z = Math.cos(newYaw) * xzlen;
  73657. localTarget.x = Math.sin(newYaw) * xzlen;
  73658. }
  73659. else {
  73660. newYaw = boneYaw - Math.PI * .75;
  73661. localTarget.z = Math.cos(newYaw) * xzlen;
  73662. localTarget.x = Math.sin(newYaw) * xzlen;
  73663. }
  73664. }
  73665. }
  73666. if (yaw != newYaw) {
  73667. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73668. localTarget.addInPlace(bonePos);
  73669. target = localTarget;
  73670. }
  73671. }
  73672. }
  73673. var zaxis = BoneLookController._tmpVecs[5];
  73674. var xaxis = BoneLookController._tmpVecs[6];
  73675. var yaxis = BoneLookController._tmpVecs[7];
  73676. var _tmpQuat = BoneLookController._tmpQuat;
  73677. target.subtractToRef(bonePos, zaxis);
  73678. zaxis.normalize();
  73679. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  73680. xaxis.normalize();
  73681. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  73682. yaxis.normalize();
  73683. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  73684. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  73685. return;
  73686. }
  73687. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  73688. return;
  73689. }
  73690. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  73691. return;
  73692. }
  73693. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  73694. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  73695. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  73696. }
  73697. if (this.slerpAmount < 1) {
  73698. if (!this._slerping) {
  73699. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  73700. }
  73701. if (this._transformYawPitch) {
  73702. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73703. }
  73704. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  73705. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  73706. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  73707. this._slerping = true;
  73708. }
  73709. else {
  73710. if (this._transformYawPitch) {
  73711. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73712. }
  73713. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  73714. this._slerping = false;
  73715. }
  73716. };
  73717. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  73718. var angDiff = ang2 - ang1;
  73719. angDiff %= Math.PI * 2;
  73720. if (angDiff > Math.PI) {
  73721. angDiff -= Math.PI * 2;
  73722. }
  73723. else if (angDiff < -Math.PI) {
  73724. angDiff += Math.PI * 2;
  73725. }
  73726. return angDiff;
  73727. };
  73728. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  73729. ang1 %= (2 * Math.PI);
  73730. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73731. ang2 %= (2 * Math.PI);
  73732. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73733. var ab = 0;
  73734. if (ang1 < ang2) {
  73735. ab = ang2 - ang1;
  73736. }
  73737. else {
  73738. ab = ang1 - ang2;
  73739. }
  73740. if (ab > Math.PI) {
  73741. ab = Math.PI * 2 - ab;
  73742. }
  73743. return ab;
  73744. };
  73745. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  73746. ang %= (2 * Math.PI);
  73747. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  73748. ang1 %= (2 * Math.PI);
  73749. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73750. ang2 %= (2 * Math.PI);
  73751. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73752. if (ang1 < ang2) {
  73753. if (ang > ang1 && ang < ang2) {
  73754. return true;
  73755. }
  73756. }
  73757. else {
  73758. if (ang > ang2 && ang < ang1) {
  73759. return true;
  73760. }
  73761. }
  73762. return false;
  73763. };
  73764. 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()];
  73765. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  73766. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73767. return BoneLookController;
  73768. }());
  73769. BABYLON.BoneLookController = BoneLookController;
  73770. })(BABYLON || (BABYLON = {}));
  73771. //# sourceMappingURL=babylon.boneLookController.js.map
  73772. "use strict";
  73773. var BABYLON;
  73774. (function (BABYLON) {
  73775. var Skeleton = /** @class */ (function () {
  73776. function Skeleton(name, id, scene) {
  73777. this.name = name;
  73778. this.id = id;
  73779. this.bones = new Array();
  73780. this.needInitialSkinMatrix = false;
  73781. this._isDirty = true;
  73782. this._meshesWithPoseMatrix = new Array();
  73783. this._identity = BABYLON.Matrix.Identity();
  73784. this._ranges = {};
  73785. this._lastAbsoluteTransformsUpdateId = -1;
  73786. /**
  73787. * Specifies if the skeleton should be serialized.
  73788. */
  73789. this.doNotSerialize = false;
  73790. // Events
  73791. /**
  73792. * An event triggered before computing the skeleton's matrices
  73793. * @type {BABYLON.Observable}
  73794. */
  73795. this.onBeforeComputeObservable = new BABYLON.Observable();
  73796. this.bones = [];
  73797. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73798. scene.skeletons.push(this);
  73799. //make sure it will recalculate the matrix next time prepare is called.
  73800. this._isDirty = true;
  73801. }
  73802. // Members
  73803. Skeleton.prototype.getTransformMatrices = function (mesh) {
  73804. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  73805. return mesh._bonesTransformMatrices;
  73806. }
  73807. if (!this._transformMatrices) {
  73808. this.prepare();
  73809. }
  73810. return this._transformMatrices;
  73811. };
  73812. Skeleton.prototype.getScene = function () {
  73813. return this._scene;
  73814. };
  73815. // Methods
  73816. /**
  73817. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  73818. */
  73819. Skeleton.prototype.toString = function (fullDetails) {
  73820. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  73821. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  73822. if (fullDetails) {
  73823. ret += ", Ranges: {";
  73824. var first = true;
  73825. for (var name_1 in this._ranges) {
  73826. if (first) {
  73827. ret += ", ";
  73828. first = false;
  73829. }
  73830. ret += name_1;
  73831. }
  73832. ret += "}";
  73833. }
  73834. return ret;
  73835. };
  73836. /**
  73837. * Get bone's index searching by name
  73838. * @param {string} name is bone's name to search for
  73839. * @return {number} Indice of the bone. Returns -1 if not found
  73840. */
  73841. Skeleton.prototype.getBoneIndexByName = function (name) {
  73842. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  73843. if (this.bones[boneIndex].name === name) {
  73844. return boneIndex;
  73845. }
  73846. }
  73847. return -1;
  73848. };
  73849. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  73850. // check name not already in use
  73851. if (!this._ranges[name]) {
  73852. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  73853. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73854. if (this.bones[i].animations[0]) {
  73855. this.bones[i].animations[0].createRange(name, from, to);
  73856. }
  73857. }
  73858. }
  73859. };
  73860. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  73861. if (deleteFrames === void 0) { deleteFrames = true; }
  73862. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73863. if (this.bones[i].animations[0]) {
  73864. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  73865. }
  73866. }
  73867. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  73868. };
  73869. Skeleton.prototype.getAnimationRange = function (name) {
  73870. return this._ranges[name];
  73871. };
  73872. /**
  73873. * Returns as an Array, all AnimationRanges defined on this skeleton
  73874. */
  73875. Skeleton.prototype.getAnimationRanges = function () {
  73876. var animationRanges = [];
  73877. var name;
  73878. var i = 0;
  73879. for (name in this._ranges) {
  73880. animationRanges[i] = this._ranges[name];
  73881. i++;
  73882. }
  73883. return animationRanges;
  73884. };
  73885. /**
  73886. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  73887. */
  73888. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  73889. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73890. if (this._ranges[name] || !source.getAnimationRange(name)) {
  73891. return false;
  73892. }
  73893. var ret = true;
  73894. var frameOffset = this._getHighestAnimationFrame() + 1;
  73895. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  73896. var boneDict = {};
  73897. var sourceBones = source.bones;
  73898. var nBones;
  73899. var i;
  73900. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  73901. boneDict[sourceBones[i].name] = sourceBones[i];
  73902. }
  73903. if (this.bones.length !== sourceBones.length) {
  73904. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  73905. ret = false;
  73906. }
  73907. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  73908. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  73909. var boneName = this.bones[i].name;
  73910. var sourceBone = boneDict[boneName];
  73911. if (sourceBone) {
  73912. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73913. }
  73914. else {
  73915. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73916. ret = false;
  73917. }
  73918. }
  73919. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73920. var range = source.getAnimationRange(name);
  73921. if (range) {
  73922. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73923. }
  73924. return ret;
  73925. };
  73926. Skeleton.prototype.returnToRest = function () {
  73927. for (var index = 0; index < this.bones.length; index++) {
  73928. this.bones[index].returnToRest();
  73929. }
  73930. };
  73931. Skeleton.prototype._getHighestAnimationFrame = function () {
  73932. var ret = 0;
  73933. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73934. if (this.bones[i].animations[0]) {
  73935. var highest = this.bones[i].animations[0].getHighestFrame();
  73936. if (ret < highest) {
  73937. ret = highest;
  73938. }
  73939. }
  73940. }
  73941. return ret;
  73942. };
  73943. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73944. var range = this.getAnimationRange(name);
  73945. if (!range) {
  73946. return null;
  73947. }
  73948. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73949. };
  73950. Skeleton.prototype._markAsDirty = function () {
  73951. this._isDirty = true;
  73952. };
  73953. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73954. this._meshesWithPoseMatrix.push(mesh);
  73955. };
  73956. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73957. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73958. if (index > -1) {
  73959. this._meshesWithPoseMatrix.splice(index, 1);
  73960. }
  73961. };
  73962. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73963. this.onBeforeComputeObservable.notifyObservers(this);
  73964. for (var index = 0; index < this.bones.length; index++) {
  73965. var bone = this.bones[index];
  73966. var parentBone = bone.getParent();
  73967. if (parentBone) {
  73968. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73969. }
  73970. else {
  73971. if (initialSkinMatrix) {
  73972. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73973. }
  73974. else {
  73975. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73976. }
  73977. }
  73978. if (bone._index !== -1) {
  73979. var mappedIndex = bone._index === null ? index : bone._index;
  73980. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73981. }
  73982. }
  73983. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73984. };
  73985. Skeleton.prototype.prepare = function () {
  73986. if (!this._isDirty) {
  73987. return;
  73988. }
  73989. if (this.needInitialSkinMatrix) {
  73990. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73991. var mesh = this._meshesWithPoseMatrix[index];
  73992. var poseMatrix = mesh.getPoseMatrix();
  73993. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73994. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73995. }
  73996. if (this._synchronizedWithMesh !== mesh) {
  73997. this._synchronizedWithMesh = mesh;
  73998. // Prepare bones
  73999. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  74000. var bone = this.bones[boneIndex];
  74001. if (!bone.getParent()) {
  74002. var matrix = bone.getBaseMatrix();
  74003. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  74004. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  74005. }
  74006. }
  74007. }
  74008. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  74009. }
  74010. }
  74011. else {
  74012. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  74013. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74014. }
  74015. this._computeTransformMatrices(this._transformMatrices, null);
  74016. }
  74017. this._isDirty = false;
  74018. this._scene._activeBones.addCount(this.bones.length, false);
  74019. };
  74020. Skeleton.prototype.getAnimatables = function () {
  74021. if (!this._animatables || this._animatables.length !== this.bones.length) {
  74022. this._animatables = [];
  74023. for (var index = 0; index < this.bones.length; index++) {
  74024. this._animatables.push(this.bones[index]);
  74025. }
  74026. }
  74027. return this._animatables;
  74028. };
  74029. Skeleton.prototype.clone = function (name, id) {
  74030. var result = new Skeleton(name, id || name, this._scene);
  74031. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74032. for (var index = 0; index < this.bones.length; index++) {
  74033. var source = this.bones[index];
  74034. var parentBone = null;
  74035. var parent_1 = source.getParent();
  74036. if (parent_1) {
  74037. var parentIndex = this.bones.indexOf(parent_1);
  74038. parentBone = result.bones[parentIndex];
  74039. }
  74040. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  74041. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  74042. }
  74043. if (this._ranges) {
  74044. result._ranges = {};
  74045. for (var rangeName in this._ranges) {
  74046. var range = this._ranges[rangeName];
  74047. if (range) {
  74048. result._ranges[rangeName] = range.clone();
  74049. }
  74050. }
  74051. }
  74052. this._isDirty = true;
  74053. return result;
  74054. };
  74055. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74056. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74057. this.bones.forEach(function (bone) {
  74058. bone.animations.forEach(function (animation) {
  74059. animation.enableBlending = true;
  74060. animation.blendingSpeed = blendingSpeed;
  74061. });
  74062. });
  74063. };
  74064. Skeleton.prototype.dispose = function () {
  74065. this._meshesWithPoseMatrix = [];
  74066. // Animations
  74067. this.getScene().stopAnimation(this);
  74068. // Remove from scene
  74069. this.getScene().removeSkeleton(this);
  74070. };
  74071. Skeleton.prototype.serialize = function () {
  74072. var serializationObject = {};
  74073. serializationObject.name = this.name;
  74074. serializationObject.id = this.id;
  74075. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  74076. serializationObject.bones = [];
  74077. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74078. for (var index = 0; index < this.bones.length; index++) {
  74079. var bone = this.bones[index];
  74080. var parent_2 = bone.getParent();
  74081. var serializedBone = {
  74082. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74083. name: bone.name,
  74084. matrix: bone.getBaseMatrix().toArray(),
  74085. rest: bone.getRestPose().toArray()
  74086. };
  74087. serializationObject.bones.push(serializedBone);
  74088. if (bone.length) {
  74089. serializedBone.length = bone.length;
  74090. }
  74091. if (bone.animations && bone.animations.length > 0) {
  74092. serializedBone.animation = bone.animations[0].serialize();
  74093. }
  74094. serializationObject.ranges = [];
  74095. for (var name in this._ranges) {
  74096. var source = this._ranges[name];
  74097. if (!source) {
  74098. continue;
  74099. }
  74100. var range = {};
  74101. range.name = name;
  74102. range.from = source.from;
  74103. range.to = source.to;
  74104. serializationObject.ranges.push(range);
  74105. }
  74106. }
  74107. return serializationObject;
  74108. };
  74109. Skeleton.Parse = function (parsedSkeleton, scene) {
  74110. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74111. if (parsedSkeleton.dimensionsAtRest) {
  74112. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74113. }
  74114. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74115. var index;
  74116. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74117. var parsedBone = parsedSkeleton.bones[index];
  74118. var parentBone = null;
  74119. if (parsedBone.parentBoneIndex > -1) {
  74120. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74121. }
  74122. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74123. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74124. if (parsedBone.length) {
  74125. bone.length = parsedBone.length;
  74126. }
  74127. if (parsedBone.animation) {
  74128. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74129. }
  74130. }
  74131. // placed after bones, so createAnimationRange can cascade down
  74132. if (parsedSkeleton.ranges) {
  74133. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74134. var data = parsedSkeleton.ranges[index];
  74135. skeleton.createAnimationRange(data.name, data.from, data.to);
  74136. }
  74137. }
  74138. return skeleton;
  74139. };
  74140. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74141. if (forceUpdate === void 0) { forceUpdate = false; }
  74142. var renderId = this._scene.getRenderId();
  74143. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74144. this.bones[0].computeAbsoluteTransforms();
  74145. this._lastAbsoluteTransformsUpdateId = renderId;
  74146. }
  74147. };
  74148. Skeleton.prototype.getPoseMatrix = function () {
  74149. var poseMatrix = null;
  74150. if (this._meshesWithPoseMatrix.length > 0) {
  74151. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74152. }
  74153. return poseMatrix;
  74154. };
  74155. Skeleton.prototype.sortBones = function () {
  74156. var bones = new Array();
  74157. var visited = new Array(this.bones.length);
  74158. for (var index = 0; index < this.bones.length; index++) {
  74159. this._sortBones(index, bones, visited);
  74160. }
  74161. this.bones = bones;
  74162. };
  74163. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74164. if (visited[index]) {
  74165. return;
  74166. }
  74167. visited[index] = true;
  74168. var bone = this.bones[index];
  74169. if (bone._index === undefined) {
  74170. bone._index = index;
  74171. }
  74172. var parentBone = bone.getParent();
  74173. if (parentBone) {
  74174. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74175. }
  74176. bones.push(bone);
  74177. };
  74178. return Skeleton;
  74179. }());
  74180. BABYLON.Skeleton = Skeleton;
  74181. })(BABYLON || (BABYLON = {}));
  74182. //# sourceMappingURL=babylon.skeleton.js.map
  74183. "use strict";
  74184. var BABYLON;
  74185. (function (BABYLON) {
  74186. var SphericalPolynomial = /** @class */ (function () {
  74187. function SphericalPolynomial() {
  74188. this.x = BABYLON.Vector3.Zero();
  74189. this.y = BABYLON.Vector3.Zero();
  74190. this.z = BABYLON.Vector3.Zero();
  74191. this.xx = BABYLON.Vector3.Zero();
  74192. this.yy = BABYLON.Vector3.Zero();
  74193. this.zz = BABYLON.Vector3.Zero();
  74194. this.xy = BABYLON.Vector3.Zero();
  74195. this.yz = BABYLON.Vector3.Zero();
  74196. this.zx = BABYLON.Vector3.Zero();
  74197. }
  74198. SphericalPolynomial.prototype.addAmbient = function (color) {
  74199. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74200. this.xx = this.xx.add(colorVector);
  74201. this.yy = this.yy.add(colorVector);
  74202. this.zz = this.zz.add(colorVector);
  74203. };
  74204. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74205. var result = new SphericalPolynomial();
  74206. result.x = harmonics.L11.scale(1.02333);
  74207. result.y = harmonics.L1_1.scale(1.02333);
  74208. result.z = harmonics.L10.scale(1.02333);
  74209. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74210. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74211. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74212. result.yz = harmonics.L2_1.scale(0.858086);
  74213. result.zx = harmonics.L21.scale(0.858086);
  74214. result.xy = harmonics.L2_2.scale(0.858086);
  74215. result.scale(1.0 / Math.PI);
  74216. return result;
  74217. };
  74218. SphericalPolynomial.prototype.scale = function (scale) {
  74219. this.x = this.x.scale(scale);
  74220. this.y = this.y.scale(scale);
  74221. this.z = this.z.scale(scale);
  74222. this.xx = this.xx.scale(scale);
  74223. this.yy = this.yy.scale(scale);
  74224. this.zz = this.zz.scale(scale);
  74225. this.yz = this.yz.scale(scale);
  74226. this.zx = this.zx.scale(scale);
  74227. this.xy = this.xy.scale(scale);
  74228. };
  74229. return SphericalPolynomial;
  74230. }());
  74231. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74232. var SphericalHarmonics = /** @class */ (function () {
  74233. function SphericalHarmonics() {
  74234. this.L00 = BABYLON.Vector3.Zero();
  74235. this.L1_1 = BABYLON.Vector3.Zero();
  74236. this.L10 = BABYLON.Vector3.Zero();
  74237. this.L11 = BABYLON.Vector3.Zero();
  74238. this.L2_2 = BABYLON.Vector3.Zero();
  74239. this.L2_1 = BABYLON.Vector3.Zero();
  74240. this.L20 = BABYLON.Vector3.Zero();
  74241. this.L21 = BABYLON.Vector3.Zero();
  74242. this.L22 = BABYLON.Vector3.Zero();
  74243. }
  74244. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74245. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74246. var c = colorVector.scale(deltaSolidAngle);
  74247. this.L00 = this.L00.add(c.scale(0.282095));
  74248. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74249. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74250. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74251. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74252. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74253. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74254. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74255. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74256. };
  74257. SphericalHarmonics.prototype.scale = function (scale) {
  74258. this.L00 = this.L00.scale(scale);
  74259. this.L1_1 = this.L1_1.scale(scale);
  74260. this.L10 = this.L10.scale(scale);
  74261. this.L11 = this.L11.scale(scale);
  74262. this.L2_2 = this.L2_2.scale(scale);
  74263. this.L2_1 = this.L2_1.scale(scale);
  74264. this.L20 = this.L20.scale(scale);
  74265. this.L21 = this.L21.scale(scale);
  74266. this.L22 = this.L22.scale(scale);
  74267. };
  74268. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74269. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74270. //
  74271. // E_lm = A_l * L_lm
  74272. //
  74273. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74274. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74275. // the scaling factors are given in equation 9.
  74276. // Constant (Band 0)
  74277. this.L00 = this.L00.scale(3.141593);
  74278. // Linear (Band 1)
  74279. this.L1_1 = this.L1_1.scale(2.094395);
  74280. this.L10 = this.L10.scale(2.094395);
  74281. this.L11 = this.L11.scale(2.094395);
  74282. // Quadratic (Band 2)
  74283. this.L2_2 = this.L2_2.scale(0.785398);
  74284. this.L2_1 = this.L2_1.scale(0.785398);
  74285. this.L20 = this.L20.scale(0.785398);
  74286. this.L21 = this.L21.scale(0.785398);
  74287. this.L22 = this.L22.scale(0.785398);
  74288. };
  74289. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74290. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74291. // L = (1/pi) * E * rho
  74292. //
  74293. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74294. this.scale(1.0 / Math.PI);
  74295. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74296. // (The pixel shader must apply albedo after texture fetches, etc).
  74297. };
  74298. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74299. var result = new SphericalHarmonics();
  74300. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74301. result.L1_1 = polynomial.y.scale(0.977204);
  74302. result.L10 = polynomial.z.scale(0.977204);
  74303. result.L11 = polynomial.x.scale(0.977204);
  74304. result.L2_2 = polynomial.xy.scale(1.16538);
  74305. result.L2_1 = polynomial.yz.scale(1.16538);
  74306. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74307. result.L21 = polynomial.zx.scale(1.16538);
  74308. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74309. result.scale(Math.PI);
  74310. return result;
  74311. };
  74312. return SphericalHarmonics;
  74313. }());
  74314. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74315. })(BABYLON || (BABYLON = {}));
  74316. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74317. "use strict";
  74318. var BABYLON;
  74319. (function (BABYLON) {
  74320. var FileFaceOrientation = /** @class */ (function () {
  74321. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74322. this.name = name;
  74323. this.worldAxisForNormal = worldAxisForNormal;
  74324. this.worldAxisForFileX = worldAxisForFileX;
  74325. this.worldAxisForFileY = worldAxisForFileY;
  74326. }
  74327. return FileFaceOrientation;
  74328. }());
  74329. ;
  74330. /**
  74331. * Helper class dealing with the extraction of spherical polynomial dataArray
  74332. * from a cube map.
  74333. */
  74334. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74335. function CubeMapToSphericalPolynomialTools() {
  74336. }
  74337. /**
  74338. * Converts a texture to the according Spherical Polynomial data.
  74339. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74340. *
  74341. * @param texture The texture to extract the information from.
  74342. * @return The Spherical Polynomial data.
  74343. */
  74344. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74345. if (!texture.isCube) {
  74346. // Only supports cube Textures currently.
  74347. return null;
  74348. }
  74349. var size = texture.getSize().width;
  74350. var right = texture.readPixels(0);
  74351. var left = texture.readPixels(1);
  74352. var up;
  74353. var down;
  74354. if (texture.isRenderTarget) {
  74355. up = texture.readPixels(3);
  74356. down = texture.readPixels(2);
  74357. }
  74358. else {
  74359. up = texture.readPixels(2);
  74360. down = texture.readPixels(3);
  74361. }
  74362. var front = texture.readPixels(4);
  74363. var back = texture.readPixels(5);
  74364. var gammaSpace = texture.gammaSpace;
  74365. // Always read as RGBA.
  74366. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74367. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74368. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74369. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74370. }
  74371. var cubeInfo = {
  74372. size: size,
  74373. right: right,
  74374. left: left,
  74375. up: up,
  74376. down: down,
  74377. front: front,
  74378. back: back,
  74379. format: format,
  74380. type: type,
  74381. gammaSpace: gammaSpace,
  74382. };
  74383. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74384. };
  74385. /**
  74386. * Converts a cubemap to the according Spherical Polynomial data.
  74387. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74388. *
  74389. * @param cubeInfo The Cube map to extract the information from.
  74390. * @return The Spherical Polynomial data.
  74391. */
  74392. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74393. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74394. var totalSolidAngle = 0.0;
  74395. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74396. var du = 2.0 / cubeInfo.size;
  74397. var dv = du;
  74398. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74399. var minUV = du * 0.5 - 1.0;
  74400. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74401. var fileFace = this.FileFaces[faceIndex];
  74402. var dataArray = cubeInfo[fileFace.name];
  74403. var v = minUV;
  74404. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74405. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74406. // Because SP is still linear, so summation is fine in that basis.
  74407. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74408. for (var y = 0; y < cubeInfo.size; y++) {
  74409. var u = minUV;
  74410. for (var x = 0; x < cubeInfo.size; x++) {
  74411. // World direction (not normalised)
  74412. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74413. worldDirection.normalize();
  74414. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74415. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74416. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74417. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74418. // Handle Integer types.
  74419. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74420. r /= 255;
  74421. g /= 255;
  74422. b /= 255;
  74423. }
  74424. // Handle Gamma space textures.
  74425. if (cubeInfo.gammaSpace) {
  74426. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74427. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74428. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74429. }
  74430. var color = new BABYLON.Color3(r, g, b);
  74431. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74432. totalSolidAngle += deltaSolidAngle;
  74433. u += du;
  74434. }
  74435. v += dv;
  74436. }
  74437. }
  74438. // Solid angle for entire sphere is 4*pi
  74439. var sphereSolidAngle = 4.0 * Math.PI;
  74440. // Adjust the solid angle to allow for how many faces we processed.
  74441. var facesProcessed = 6.0;
  74442. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74443. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74444. // This is needed because the numerical integration over the cube uses a
  74445. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74446. // and also to compensate for accumulative error due to float precision in the summation.
  74447. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74448. sphericalHarmonics.scale(correctionFactor);
  74449. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74450. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74451. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74452. };
  74453. CubeMapToSphericalPolynomialTools.FileFaces = [
  74454. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74455. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74456. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74457. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74458. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74459. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74460. ];
  74461. return CubeMapToSphericalPolynomialTools;
  74462. }());
  74463. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74464. })(BABYLON || (BABYLON = {}));
  74465. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74466. "use strict";
  74467. var BABYLON;
  74468. (function (BABYLON) {
  74469. /**
  74470. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74471. */
  74472. var PanoramaToCubeMapTools = /** @class */ (function () {
  74473. function PanoramaToCubeMapTools() {
  74474. }
  74475. /**
  74476. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74477. *
  74478. * @param float32Array The source data.
  74479. * @param inputWidth The width of the input panorama.
  74480. * @param inputhHeight The height of the input panorama.
  74481. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74482. * @return The cubemap data
  74483. */
  74484. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74485. if (!float32Array) {
  74486. throw "ConvertPanoramaToCubemap: input cannot be null";
  74487. }
  74488. if (float32Array.length != inputWidth * inputHeight * 3) {
  74489. throw "ConvertPanoramaToCubemap: input size is wrong";
  74490. }
  74491. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74492. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74493. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74494. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74495. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74496. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74497. return {
  74498. front: textureFront,
  74499. back: textureBack,
  74500. left: textureLeft,
  74501. right: textureRight,
  74502. up: textureUp,
  74503. down: textureDown,
  74504. size: size,
  74505. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74506. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74507. gammaSpace: false,
  74508. };
  74509. };
  74510. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74511. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74512. var textureArray = new Float32Array(buffer);
  74513. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74514. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74515. var dy = 1 / texSize;
  74516. var fy = 0;
  74517. for (var y = 0; y < texSize; y++) {
  74518. var xv1 = faceData[0];
  74519. var xv2 = faceData[2];
  74520. for (var x = 0; x < texSize; x++) {
  74521. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74522. v.normalize();
  74523. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74524. // 3 channels per pixels
  74525. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74526. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74527. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74528. xv1 = xv1.add(rotDX1);
  74529. xv2 = xv2.add(rotDX2);
  74530. }
  74531. fy += dy;
  74532. }
  74533. return textureArray;
  74534. };
  74535. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74536. var theta = Math.atan2(vDir.z, vDir.x);
  74537. var phi = Math.acos(vDir.y);
  74538. while (theta < -Math.PI)
  74539. theta += 2 * Math.PI;
  74540. while (theta > Math.PI)
  74541. theta -= 2 * Math.PI;
  74542. var dx = theta / Math.PI;
  74543. var dy = phi / Math.PI;
  74544. // recenter.
  74545. dx = dx * 0.5 + 0.5;
  74546. var px = Math.round(dx * inputWidth);
  74547. if (px < 0)
  74548. px = 0;
  74549. else if (px >= inputWidth)
  74550. px = inputWidth - 1;
  74551. var py = Math.round(dy * inputHeight);
  74552. if (py < 0)
  74553. py = 0;
  74554. else if (py >= inputHeight)
  74555. py = inputHeight - 1;
  74556. var inputY = (inputHeight - py - 1);
  74557. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  74558. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  74559. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  74560. return {
  74561. r: r,
  74562. g: g,
  74563. b: b
  74564. };
  74565. };
  74566. PanoramaToCubeMapTools.FACE_FRONT = [
  74567. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74568. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74569. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74570. new BABYLON.Vector3(1.0, 1.0, -1.0)
  74571. ];
  74572. PanoramaToCubeMapTools.FACE_BACK = [
  74573. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74574. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74575. new BABYLON.Vector3(1.0, 1.0, 1.0),
  74576. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  74577. ];
  74578. PanoramaToCubeMapTools.FACE_RIGHT = [
  74579. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74580. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74581. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74582. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74583. ];
  74584. PanoramaToCubeMapTools.FACE_LEFT = [
  74585. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74586. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74587. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74588. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  74589. ];
  74590. PanoramaToCubeMapTools.FACE_DOWN = [
  74591. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74592. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74593. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74594. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74595. ];
  74596. PanoramaToCubeMapTools.FACE_UP = [
  74597. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74598. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74599. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74600. new BABYLON.Vector3(1.0, -1.0, -1.0)
  74601. ];
  74602. return PanoramaToCubeMapTools;
  74603. }());
  74604. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  74605. })(BABYLON || (BABYLON = {}));
  74606. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  74607. "use strict";
  74608. var BABYLON;
  74609. (function (BABYLON) {
  74610. ;
  74611. /**
  74612. * This groups tools to convert HDR texture to native colors array.
  74613. */
  74614. var HDRTools = /** @class */ (function () {
  74615. function HDRTools() {
  74616. }
  74617. HDRTools.Ldexp = function (mantissa, exponent) {
  74618. if (exponent > 1023) {
  74619. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  74620. }
  74621. if (exponent < -1074) {
  74622. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  74623. }
  74624. return mantissa * Math.pow(2, exponent);
  74625. };
  74626. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74627. if (exponent > 0) {
  74628. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74629. float32array[index + 0] = red * exponent;
  74630. float32array[index + 1] = green * exponent;
  74631. float32array[index + 2] = blue * exponent;
  74632. }
  74633. else {
  74634. float32array[index + 0] = 0;
  74635. float32array[index + 1] = 0;
  74636. float32array[index + 2] = 0;
  74637. }
  74638. };
  74639. HDRTools.readStringLine = function (uint8array, startIndex) {
  74640. var line = "";
  74641. var character = "";
  74642. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74643. character = String.fromCharCode(uint8array[i]);
  74644. if (character == "\n") {
  74645. break;
  74646. }
  74647. line += character;
  74648. }
  74649. return line;
  74650. };
  74651. /**
  74652. * Reads header information from an RGBE texture stored in a native array.
  74653. * More information on this format are available here:
  74654. * https://en.wikipedia.org/wiki/RGBE_image_format
  74655. *
  74656. * @param uint8array The binary file stored in native array.
  74657. * @return The header information.
  74658. */
  74659. HDRTools.RGBE_ReadHeader = function (uint8array) {
  74660. var height = 0;
  74661. var width = 0;
  74662. var line = this.readStringLine(uint8array, 0);
  74663. if (line[0] != '#' || line[1] != '?') {
  74664. throw "Bad HDR Format.";
  74665. }
  74666. var endOfHeader = false;
  74667. var findFormat = false;
  74668. var lineIndex = 0;
  74669. do {
  74670. lineIndex += (line.length + 1);
  74671. line = this.readStringLine(uint8array, lineIndex);
  74672. if (line == "FORMAT=32-bit_rle_rgbe") {
  74673. findFormat = true;
  74674. }
  74675. else if (line.length == 0) {
  74676. endOfHeader = true;
  74677. }
  74678. } while (!endOfHeader);
  74679. if (!findFormat) {
  74680. throw "HDR Bad header format, unsupported FORMAT";
  74681. }
  74682. lineIndex += (line.length + 1);
  74683. line = this.readStringLine(uint8array, lineIndex);
  74684. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  74685. var match = sizeRegexp.exec(line);
  74686. // TODO. Support +Y and -X if needed.
  74687. if (!match || match.length < 3) {
  74688. throw "HDR Bad header format, no size";
  74689. }
  74690. width = parseInt(match[2]);
  74691. height = parseInt(match[1]);
  74692. if (width < 8 || width > 0x7fff) {
  74693. throw "HDR Bad header format, unsupported size";
  74694. }
  74695. lineIndex += (line.length + 1);
  74696. return {
  74697. height: height,
  74698. width: width,
  74699. dataPosition: lineIndex
  74700. };
  74701. };
  74702. /**
  74703. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  74704. * This RGBE texture needs to store the information as a panorama.
  74705. *
  74706. * More information on this format are available here:
  74707. * https://en.wikipedia.org/wiki/RGBE_image_format
  74708. *
  74709. * @param buffer The binary file stored in an array buffer.
  74710. * @param size The expected size of the extracted cubemap.
  74711. * @return The Cube Map information.
  74712. */
  74713. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  74714. var uint8array = new Uint8Array(buffer);
  74715. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  74716. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74717. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  74718. return cubeMapData;
  74719. };
  74720. /**
  74721. * Returns the pixels data extracted from an RGBE texture.
  74722. * This pixels will be stored left to right up to down in the R G B order in one array.
  74723. *
  74724. * More information on this format are available here:
  74725. * https://en.wikipedia.org/wiki/RGBE_image_format
  74726. *
  74727. * @param uint8array The binary file stored in an array buffer.
  74728. * @param hdrInfo The header information of the file.
  74729. * @return The pixels data in RGB right to left up to down order.
  74730. */
  74731. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  74732. // Keep for multi format supports.
  74733. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74734. };
  74735. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  74736. var num_scanlines = hdrInfo.height;
  74737. var scanline_width = hdrInfo.width;
  74738. var a, b, c, d, count;
  74739. var dataIndex = hdrInfo.dataPosition;
  74740. var index = 0, endIndex = 0, i = 0;
  74741. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  74742. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  74743. // 3 channels of 4 bytes per pixel in float.
  74744. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  74745. var resultArray = new Float32Array(resultBuffer);
  74746. // read in each successive scanline
  74747. while (num_scanlines > 0) {
  74748. a = uint8array[dataIndex++];
  74749. b = uint8array[dataIndex++];
  74750. c = uint8array[dataIndex++];
  74751. d = uint8array[dataIndex++];
  74752. if (a != 2 || b != 2 || (c & 0x80)) {
  74753. // this file is not run length encoded
  74754. throw "HDR Bad header format, not RLE";
  74755. }
  74756. if (((c << 8) | d) != scanline_width) {
  74757. throw "HDR Bad header format, wrong scan line width";
  74758. }
  74759. index = 0;
  74760. // read each of the four channels for the scanline into the buffer
  74761. for (i = 0; i < 4; i++) {
  74762. endIndex = (i + 1) * scanline_width;
  74763. while (index < endIndex) {
  74764. a = uint8array[dataIndex++];
  74765. b = uint8array[dataIndex++];
  74766. if (a > 128) {
  74767. // a run of the same value
  74768. count = a - 128;
  74769. if ((count == 0) || (count > endIndex - index)) {
  74770. throw "HDR Bad Format, bad scanline data (run)";
  74771. }
  74772. while (count-- > 0) {
  74773. scanLineArray[index++] = b;
  74774. }
  74775. }
  74776. else {
  74777. // a non-run
  74778. count = a;
  74779. if ((count == 0) || (count > endIndex - index)) {
  74780. throw "HDR Bad Format, bad scanline data (non-run)";
  74781. }
  74782. scanLineArray[index++] = b;
  74783. if (--count > 0) {
  74784. for (var j = 0; j < count; j++) {
  74785. scanLineArray[index++] = uint8array[dataIndex++];
  74786. }
  74787. }
  74788. }
  74789. }
  74790. }
  74791. // now convert data from buffer into floats
  74792. for (i = 0; i < scanline_width; i++) {
  74793. a = scanLineArray[i];
  74794. b = scanLineArray[i + scanline_width];
  74795. c = scanLineArray[i + 2 * scanline_width];
  74796. d = scanLineArray[i + 3 * scanline_width];
  74797. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  74798. }
  74799. num_scanlines--;
  74800. }
  74801. return resultArray;
  74802. };
  74803. return HDRTools;
  74804. }());
  74805. BABYLON.HDRTools = HDRTools;
  74806. })(BABYLON || (BABYLON = {}));
  74807. //# sourceMappingURL=babylon.hdr.js.map
  74808. "use strict";
  74809. var BABYLON;
  74810. (function (BABYLON) {
  74811. /**
  74812. * This represents a texture coming from an HDR input.
  74813. *
  74814. * The only supported format is currently panorama picture stored in RGBE format.
  74815. * Example of such files can be found on HDRLib: http://hdrlib.com/
  74816. */
  74817. var HDRCubeTexture = /** @class */ (function (_super) {
  74818. __extends(HDRCubeTexture, _super);
  74819. /**
  74820. * Instantiates an HDRTexture from the following parameters.
  74821. *
  74822. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  74823. * @param scene The scene the texture will be used in
  74824. * @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.
  74825. * @param noMipmap Forces to not generate the mipmap if true
  74826. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  74827. * @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)
  74828. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  74829. */
  74830. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  74831. if (noMipmap === void 0) { noMipmap = false; }
  74832. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74833. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74834. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74835. if (onLoad === void 0) { onLoad = null; }
  74836. if (onError === void 0) { onError = null; }
  74837. var _this = _super.call(this, scene) || this;
  74838. _this._useInGammaSpace = false;
  74839. _this._generateHarmonics = true;
  74840. _this._isBABYLONPreprocessed = false;
  74841. _this._onLoad = null;
  74842. _this._onError = null;
  74843. /**
  74844. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  74845. */
  74846. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  74847. /**
  74848. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  74849. * This is usefull at run time to apply the good shader.
  74850. */
  74851. _this.isPMREM = false;
  74852. _this._isBlocking = true;
  74853. /**
  74854. * Gets or sets the center of the bounding box associated with the cube texture
  74855. * It must define where the camera used to render the texture was set
  74856. */
  74857. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  74858. if (!url) {
  74859. return _this;
  74860. }
  74861. _this.name = url;
  74862. _this.url = url;
  74863. _this.hasAlpha = false;
  74864. _this.isCube = true;
  74865. _this._textureMatrix = BABYLON.Matrix.Identity();
  74866. _this._onLoad = onLoad;
  74867. _this._onError = onError;
  74868. _this.gammaSpace = false;
  74869. var caps = scene.getEngine().getCaps();
  74870. if (size) {
  74871. _this._isBABYLONPreprocessed = false;
  74872. _this._noMipmap = noMipmap;
  74873. _this._size = size;
  74874. _this._useInGammaSpace = useInGammaSpace;
  74875. _this._usePMREMGenerator = usePMREMGenerator &&
  74876. caps.textureLOD &&
  74877. caps.textureFloat &&
  74878. !_this._useInGammaSpace;
  74879. }
  74880. else {
  74881. _this._isBABYLONPreprocessed = true;
  74882. _this._noMipmap = false;
  74883. _this._useInGammaSpace = false;
  74884. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  74885. !_this._useInGammaSpace;
  74886. }
  74887. _this.isPMREM = _this._usePMREMGenerator;
  74888. _this._texture = _this._getFromCache(url, _this._noMipmap);
  74889. if (!_this._texture) {
  74890. if (!scene.useDelayedTextureLoading) {
  74891. _this.loadTexture();
  74892. }
  74893. else {
  74894. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  74895. }
  74896. }
  74897. return _this;
  74898. }
  74899. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  74900. /**
  74901. * Gets wether or not the texture is blocking during loading.
  74902. */
  74903. get: function () {
  74904. return this._isBlocking;
  74905. },
  74906. /**
  74907. * Sets wether or not the texture is blocking during loading.
  74908. */
  74909. set: function (value) {
  74910. this._isBlocking = value;
  74911. },
  74912. enumerable: true,
  74913. configurable: true
  74914. });
  74915. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  74916. get: function () {
  74917. return this._boundingBoxSize;
  74918. },
  74919. /**
  74920. * Gets or sets the size of the bounding box associated with the cube texture
  74921. * When defined, the cubemap will switch to local mode
  74922. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74923. * @example https://www.babylonjs-playground.com/#RNASML
  74924. */
  74925. set: function (value) {
  74926. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74927. return;
  74928. }
  74929. this._boundingBoxSize = value;
  74930. var scene = this.getScene();
  74931. if (scene) {
  74932. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74933. }
  74934. },
  74935. enumerable: true,
  74936. configurable: true
  74937. });
  74938. /**
  74939. * Occurs when the file is a preprocessed .babylon.hdr file.
  74940. */
  74941. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74942. var _this = this;
  74943. var mipLevels = 0;
  74944. var floatArrayView = null;
  74945. var scene = this.getScene();
  74946. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74947. var mips = new Array();
  74948. if (!floatArrayView) {
  74949. return mips;
  74950. }
  74951. var startIndex = 30;
  74952. for (var level = 0; level < mipLevels; level++) {
  74953. mips.push([]);
  74954. // Fill each pixel of the mip level.
  74955. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74956. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74957. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74958. mips[level].push(faceData);
  74959. startIndex += faceSize;
  74960. }
  74961. }
  74962. return mips;
  74963. } : null;
  74964. var callback = function (buffer) {
  74965. var scene = _this.getScene();
  74966. if (!scene) {
  74967. return null;
  74968. }
  74969. // Create Native Array Views
  74970. var intArrayView = new Int32Array(buffer);
  74971. floatArrayView = new Float32Array(buffer);
  74972. // Fill header.
  74973. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74974. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74975. // Update Texture Information.
  74976. if (!_this._texture) {
  74977. return null;
  74978. }
  74979. _this._texture.updateSize(_this._size, _this._size);
  74980. // Fill polynomial information.
  74981. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74982. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74983. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74984. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74985. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74986. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74987. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74988. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74989. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74990. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74991. _this.sphericalPolynomial = sphericalPolynomial;
  74992. // Fill pixel data.
  74993. mipLevels = intArrayView[29]; // Number of mip levels.
  74994. var startIndex = 30;
  74995. var data = [];
  74996. var faceSize = Math.pow(_this._size, 2) * 3;
  74997. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74998. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74999. startIndex += faceSize;
  75000. }
  75001. var results = [];
  75002. var byteArray = null;
  75003. // Push each faces.
  75004. for (var k = 0; k < 6; k++) {
  75005. var dataFace = null;
  75006. // To be deprecated.
  75007. if (version === 1) {
  75008. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  75009. dataFace = data[j];
  75010. }
  75011. // If special cases.
  75012. if (!mipmapGenerator && dataFace) {
  75013. if (!scene.getEngine().getCaps().textureFloat) {
  75014. // 3 channels of 1 bytes per pixel in bytes.
  75015. var byteBuffer = new ArrayBuffer(faceSize);
  75016. byteArray = new Uint8Array(byteBuffer);
  75017. }
  75018. for (var i = 0; i < _this._size * _this._size; i++) {
  75019. // Put in gamma space if requested.
  75020. if (_this._useInGammaSpace) {
  75021. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75022. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75023. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75024. }
  75025. // Convert to int texture for fallback.
  75026. if (byteArray) {
  75027. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75028. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75029. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75030. // May use luminance instead if the result is not accurate.
  75031. var max = Math.max(Math.max(r, g), b);
  75032. if (max > 255) {
  75033. var scale = 255 / max;
  75034. r *= scale;
  75035. g *= scale;
  75036. b *= scale;
  75037. }
  75038. byteArray[(i * 3) + 0] = r;
  75039. byteArray[(i * 3) + 1] = g;
  75040. byteArray[(i * 3) + 2] = b;
  75041. }
  75042. }
  75043. }
  75044. // Fill the array accordingly.
  75045. if (byteArray) {
  75046. results.push(byteArray);
  75047. }
  75048. else {
  75049. results.push(dataFace);
  75050. }
  75051. }
  75052. return results;
  75053. };
  75054. if (scene) {
  75055. 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);
  75056. }
  75057. };
  75058. /**
  75059. * Occurs when the file is raw .hdr file.
  75060. */
  75061. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75062. var _this = this;
  75063. var callback = function (buffer) {
  75064. var scene = _this.getScene();
  75065. if (!scene) {
  75066. return null;
  75067. }
  75068. // Extract the raw linear data.
  75069. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75070. // Generate harmonics if needed.
  75071. if (_this._generateHarmonics) {
  75072. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75073. _this.sphericalPolynomial = sphericalPolynomial;
  75074. }
  75075. var results = [];
  75076. var byteArray = null;
  75077. // Push each faces.
  75078. for (var j = 0; j < 6; j++) {
  75079. // Create uintarray fallback.
  75080. if (!scene.getEngine().getCaps().textureFloat) {
  75081. // 3 channels of 1 bytes per pixel in bytes.
  75082. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75083. byteArray = new Uint8Array(byteBuffer);
  75084. }
  75085. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75086. // If special cases.
  75087. if (_this._useInGammaSpace || byteArray) {
  75088. for (var i = 0; i < _this._size * _this._size; i++) {
  75089. // Put in gamma space if requested.
  75090. if (_this._useInGammaSpace) {
  75091. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75092. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75093. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75094. }
  75095. // Convert to int texture for fallback.
  75096. if (byteArray) {
  75097. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75098. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75099. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75100. // May use luminance instead if the result is not accurate.
  75101. var max = Math.max(Math.max(r, g), b);
  75102. if (max > 255) {
  75103. var scale = 255 / max;
  75104. r *= scale;
  75105. g *= scale;
  75106. b *= scale;
  75107. }
  75108. byteArray[(i * 3) + 0] = r;
  75109. byteArray[(i * 3) + 1] = g;
  75110. byteArray[(i * 3) + 2] = b;
  75111. }
  75112. }
  75113. }
  75114. if (byteArray) {
  75115. results.push(byteArray);
  75116. }
  75117. else {
  75118. results.push(dataFace);
  75119. }
  75120. }
  75121. return results;
  75122. };
  75123. var mipmapGenerator = null;
  75124. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75125. // if (!this._noMipmap &&
  75126. // this._usePMREMGenerator) {
  75127. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75128. // // Custom setup of the generator matching with the PBR shader values.
  75129. // var generator = new BABYLON.PMREMGenerator(data,
  75130. // this._size,
  75131. // this._size,
  75132. // 0,
  75133. // 3,
  75134. // this.getScene().getEngine().getCaps().textureFloat,
  75135. // 2048,
  75136. // 0.25,
  75137. // false,
  75138. // true);
  75139. // return generator.filterCubeMap();
  75140. // };
  75141. // }
  75142. var scene = this.getScene();
  75143. if (scene) {
  75144. 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);
  75145. }
  75146. };
  75147. /**
  75148. * Starts the loading process of the texture.
  75149. */
  75150. HDRCubeTexture.prototype.loadTexture = function () {
  75151. if (this._isBABYLONPreprocessed) {
  75152. this.loadBabylonTexture();
  75153. }
  75154. else {
  75155. this.loadHDRTexture();
  75156. }
  75157. };
  75158. HDRCubeTexture.prototype.clone = function () {
  75159. var scene = this.getScene();
  75160. if (!scene) {
  75161. return this;
  75162. }
  75163. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75164. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75165. // Base texture
  75166. newTexture.level = this.level;
  75167. newTexture.wrapU = this.wrapU;
  75168. newTexture.wrapV = this.wrapV;
  75169. newTexture.coordinatesIndex = this.coordinatesIndex;
  75170. newTexture.coordinatesMode = this.coordinatesMode;
  75171. return newTexture;
  75172. };
  75173. // Methods
  75174. HDRCubeTexture.prototype.delayLoad = function () {
  75175. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75176. return;
  75177. }
  75178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75179. this._texture = this._getFromCache(this.url, this._noMipmap);
  75180. if (!this._texture) {
  75181. this.loadTexture();
  75182. }
  75183. };
  75184. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75185. return this._textureMatrix;
  75186. };
  75187. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75188. this._textureMatrix = value;
  75189. };
  75190. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75191. var texture = null;
  75192. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75193. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75194. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75195. texture.name = parsedTexture.name;
  75196. texture.hasAlpha = parsedTexture.hasAlpha;
  75197. texture.level = parsedTexture.level;
  75198. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75199. texture.isBlocking = parsedTexture.isBlocking;
  75200. }
  75201. if (texture) {
  75202. if (parsedTexture.boundingBoxPosition) {
  75203. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75204. }
  75205. if (parsedTexture.boundingBoxSize) {
  75206. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75207. }
  75208. }
  75209. return texture;
  75210. };
  75211. HDRCubeTexture.prototype.serialize = function () {
  75212. if (!this.name) {
  75213. return null;
  75214. }
  75215. var serializationObject = {};
  75216. serializationObject.name = this.name;
  75217. serializationObject.hasAlpha = this.hasAlpha;
  75218. serializationObject.isCube = true;
  75219. serializationObject.level = this.level;
  75220. serializationObject.size = this._size;
  75221. serializationObject.coordinatesMode = this.coordinatesMode;
  75222. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75223. serializationObject.generateHarmonics = this._generateHarmonics;
  75224. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75225. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75226. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75227. serializationObject.noMipmap = this._noMipmap;
  75228. serializationObject.isBlocking = this._isBlocking;
  75229. return serializationObject;
  75230. };
  75231. /**
  75232. * Saves as a file the data contained in the texture in a binary format.
  75233. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75234. * as the spherical used in the lighting.
  75235. * @param url The HDR file url.
  75236. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75237. * @param onError Method called if any error happens during download.
  75238. * @return The packed binary data.
  75239. */
  75240. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75241. if (onError === void 0) { onError = null; }
  75242. var callback = function (buffer) {
  75243. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75244. // Returns a URL you can use as a href.
  75245. var objUrl = window.URL.createObjectURL(data);
  75246. // Simulates a link to it and click to dowload.
  75247. var a = document.createElement("a");
  75248. document.body.appendChild(a);
  75249. a.style.display = "none";
  75250. a.href = objUrl;
  75251. a.download = "envmap.babylon.hdr";
  75252. a.click();
  75253. };
  75254. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75255. };
  75256. /**
  75257. * Serializes the data contained in the texture in a binary format.
  75258. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75259. * as the spherical used in the lighting.
  75260. * @param url The HDR file url.
  75261. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75262. * @param onError Method called if any error happens during download.
  75263. * @return The packed binary data.
  75264. */
  75265. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75266. if (onError === void 0) { onError = null; }
  75267. // Needs the url tho create the texture.
  75268. if (!url) {
  75269. return;
  75270. }
  75271. // Check Power of two size.
  75272. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75273. return;
  75274. }
  75275. // Coming Back in 3.x.
  75276. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75277. };
  75278. HDRCubeTexture._facesMapping = [
  75279. "right",
  75280. "left",
  75281. "up",
  75282. "down",
  75283. "front",
  75284. "back"
  75285. ];
  75286. return HDRCubeTexture;
  75287. }(BABYLON.BaseTexture));
  75288. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75289. })(BABYLON || (BABYLON = {}));
  75290. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75291. "use strict";
  75292. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75293. // Huge respect for a such great lib.
  75294. // Earcut license:
  75295. // Copyright (c) 2016, Mapbox
  75296. //
  75297. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75298. // with or without fee is hereby granted, provided that the above copyright notice
  75299. // and this permission notice appear in all copies.
  75300. //
  75301. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75302. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75303. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75304. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75305. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75306. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75307. // THIS SOFTWARE.
  75308. var Earcut;
  75309. (function (Earcut) {
  75310. /**
  75311. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75312. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75313. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  75314. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75315. */
  75316. function earcut(data, holeIndices, dim) {
  75317. dim = dim || 2;
  75318. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75319. if (!outerNode)
  75320. return triangles;
  75321. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75322. if (hasHoles)
  75323. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75324. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75325. if (data.length > 80 * dim) {
  75326. minX = maxX = data[0];
  75327. minY = maxY = data[1];
  75328. for (var i = dim; i < outerLen; i += dim) {
  75329. x = data[i];
  75330. y = data[i + 1];
  75331. if (x < minX)
  75332. minX = x;
  75333. if (y < minY)
  75334. minY = y;
  75335. if (x > maxX)
  75336. maxX = x;
  75337. if (y > maxY)
  75338. maxY = y;
  75339. }
  75340. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75341. size = Math.max(maxX - minX, maxY - minY);
  75342. }
  75343. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75344. return triangles;
  75345. }
  75346. Earcut.earcut = earcut;
  75347. var Node = /** @class */ (function () {
  75348. function Node(i, x, y) {
  75349. this.i = i;
  75350. this.x = x;
  75351. this.y = y;
  75352. this.prev = null;
  75353. this.next = null;
  75354. this.z = null;
  75355. this.prevZ = null;
  75356. this.nextZ = null;
  75357. this.steiner = false;
  75358. }
  75359. return Node;
  75360. }());
  75361. // create a circular doubly linked list from polygon points in the specified winding order
  75362. function linkedList(data, start, end, dim, clockwise) {
  75363. var i, last = null;
  75364. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75365. for (i = start; i < end; i += dim)
  75366. last = insertNode(i, data[i], data[i + 1], last);
  75367. }
  75368. else {
  75369. for (i = end - dim; i >= start; i -= dim)
  75370. last = insertNode(i, data[i], data[i + 1], last);
  75371. }
  75372. if (last && equals(last, last.next)) {
  75373. removeNode(last);
  75374. last = last.next;
  75375. }
  75376. return last;
  75377. }
  75378. // eliminate colinear or duplicate points
  75379. function filterPoints(start, end) {
  75380. if (!start)
  75381. return start;
  75382. if (!end)
  75383. end = start;
  75384. var p = start, again;
  75385. do {
  75386. again = false;
  75387. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75388. removeNode(p);
  75389. p = end = p.prev;
  75390. if (p === p.next)
  75391. return undefined;
  75392. again = true;
  75393. }
  75394. else {
  75395. p = p.next;
  75396. }
  75397. } while (again || p !== end);
  75398. return end;
  75399. }
  75400. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75401. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75402. if (!ear)
  75403. return;
  75404. // interlink polygon nodes in z-order
  75405. if (!pass && size)
  75406. indexCurve(ear, minX, minY, size);
  75407. var stop = ear, prev, next;
  75408. // iterate through ears, slicing them one by one
  75409. while (ear.prev !== ear.next) {
  75410. prev = ear.prev;
  75411. next = ear.next;
  75412. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75413. // cut off the triangle
  75414. triangles.push(prev.i / dim);
  75415. triangles.push(ear.i / dim);
  75416. triangles.push(next.i / dim);
  75417. removeNode(ear);
  75418. // skipping the next vertice leads to less sliver triangles
  75419. ear = next.next;
  75420. stop = next.next;
  75421. continue;
  75422. }
  75423. ear = next;
  75424. // if we looped through the whole remaining polygon and can't find any more ears
  75425. if (ear === stop) {
  75426. // try filtering points and slicing again
  75427. if (!pass) {
  75428. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75429. // if this didn't work, try curing all small self-intersections locally
  75430. }
  75431. else if (pass === 1) {
  75432. ear = cureLocalIntersections(ear, triangles, dim);
  75433. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75434. // as a last resort, try splitting the remaining polygon into two
  75435. }
  75436. else if (pass === 2) {
  75437. splitEarcut(ear, triangles, dim, minX, minY, size);
  75438. }
  75439. break;
  75440. }
  75441. }
  75442. }
  75443. // check whether a polygon node forms a valid ear with adjacent nodes
  75444. function isEar(ear) {
  75445. var a = ear.prev, b = ear, c = ear.next;
  75446. if (area(a, b, c) >= 0)
  75447. return false; // reflex, can't be an ear
  75448. // now make sure we don't have other points inside the potential ear
  75449. var p = ear.next.next;
  75450. while (p !== ear.prev) {
  75451. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75452. area(p.prev, p, p.next) >= 0)
  75453. return false;
  75454. p = p.next;
  75455. }
  75456. return true;
  75457. }
  75458. function isEarHashed(ear, minX, minY, size) {
  75459. var a = ear.prev, b = ear, c = ear.next;
  75460. if (area(a, b, c) >= 0)
  75461. return false; // reflex, can't be an ear
  75462. // triangle bbox; min & max are calculated like this for speed
  75463. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  75464. // z-order range for the current triangle bbox;
  75465. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75466. // first look for points inside the triangle in increasing z-order
  75467. var p = ear.nextZ;
  75468. while (p && p.z <= maxZ) {
  75469. if (p !== ear.prev &&
  75470. p !== ear.next &&
  75471. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75472. area(p.prev, p, p.next) >= 0)
  75473. return false;
  75474. p = p.nextZ;
  75475. }
  75476. // then look for points in decreasing z-order
  75477. p = ear.prevZ;
  75478. while (p && p.z >= minZ) {
  75479. if (p !== ear.prev &&
  75480. p !== ear.next &&
  75481. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75482. area(p.prev, p, p.next) >= 0)
  75483. return false;
  75484. p = p.prevZ;
  75485. }
  75486. return true;
  75487. }
  75488. // go through all polygon nodes and cure small local self-intersections
  75489. function cureLocalIntersections(start, triangles, dim) {
  75490. var p = start;
  75491. do {
  75492. var a = p.prev, b = p.next.next;
  75493. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75494. triangles.push(a.i / dim);
  75495. triangles.push(p.i / dim);
  75496. triangles.push(b.i / dim);
  75497. // remove two nodes involved
  75498. removeNode(p);
  75499. removeNode(p.next);
  75500. p = start = b;
  75501. }
  75502. p = p.next;
  75503. } while (p !== start);
  75504. return p;
  75505. }
  75506. // try splitting polygon into two and triangulate them independently
  75507. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75508. // look for a valid diagonal that divides the polygon into two
  75509. var a = start;
  75510. do {
  75511. var b = a.next.next;
  75512. while (b !== a.prev) {
  75513. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75514. // split the polygon in two by the diagonal
  75515. var c = splitPolygon(a, b);
  75516. // filter colinear points around the cuts
  75517. a = filterPoints(a, a.next);
  75518. c = filterPoints(c, c.next);
  75519. // run earcut on each half
  75520. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75521. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75522. return;
  75523. }
  75524. b = b.next;
  75525. }
  75526. a = a.next;
  75527. } while (a !== start);
  75528. }
  75529. // link every hole into the outer loop, producing a single-ring polygon without holes
  75530. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75531. var queue = [], i, len, start, end, list;
  75532. for (i = 0, len = holeIndices.length; i < len; i++) {
  75533. start = holeIndices[i] * dim;
  75534. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75535. list = linkedList(data, start, end, dim, false);
  75536. if (list === list.next)
  75537. list.steiner = true;
  75538. queue.push(getLeftmost(list));
  75539. }
  75540. queue.sort(compareX);
  75541. // process holes from left to right
  75542. for (i = 0; i < queue.length; i++) {
  75543. eliminateHole(queue[i], outerNode);
  75544. outerNode = filterPoints(outerNode, outerNode.next);
  75545. }
  75546. return outerNode;
  75547. }
  75548. function compareX(a, b) {
  75549. return a.x - b.x;
  75550. }
  75551. // find a bridge between vertices that connects hole with an outer ring and and link it
  75552. function eliminateHole(hole, outerNode) {
  75553. outerNode = findHoleBridge(hole, outerNode);
  75554. if (outerNode) {
  75555. var b = splitPolygon(outerNode, hole);
  75556. filterPoints(b, b.next);
  75557. }
  75558. }
  75559. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  75560. function findHoleBridge(hole, outerNode) {
  75561. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  75562. // find a segment intersected by a ray from the hole's leftmost point to the left;
  75563. // segment's endpoint with lesser x will be potential connection point
  75564. do {
  75565. if (hy <= p.y && hy >= p.next.y) {
  75566. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  75567. if (x <= hx && x > qx) {
  75568. qx = x;
  75569. if (x === hx) {
  75570. if (hy === p.y)
  75571. return p;
  75572. if (hy === p.next.y)
  75573. return p.next;
  75574. }
  75575. m = p.x < p.next.x ? p : p.next;
  75576. }
  75577. }
  75578. p = p.next;
  75579. } while (p !== outerNode);
  75580. if (!m)
  75581. return null;
  75582. if (hx === qx)
  75583. return m.prev; // hole touches outer segment; pick lower endpoint
  75584. // look for points inside the triangle of hole point, segment intersection and endpoint;
  75585. // if there are no points found, we have a valid connection;
  75586. // otherwise choose the point of the minimum angle with the ray as connection point
  75587. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  75588. p = m.next;
  75589. while (p !== stop) {
  75590. if (hx >= p.x &&
  75591. p.x >= mx &&
  75592. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  75593. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  75594. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  75595. m = p;
  75596. tanMin = tan;
  75597. }
  75598. }
  75599. p = p.next;
  75600. }
  75601. return m;
  75602. }
  75603. // interlink polygon nodes in z-order
  75604. function indexCurve(start, minX, minY, size) {
  75605. var p = start;
  75606. do {
  75607. if (p.z === null)
  75608. p.z = zOrder(p.x, p.y, minX, minY, size);
  75609. p.prevZ = p.prev;
  75610. p.nextZ = p.next;
  75611. p = p.next;
  75612. } while (p !== start);
  75613. p.prevZ.nextZ = null;
  75614. p.prevZ = null;
  75615. sortLinked(p);
  75616. }
  75617. // Simon Tatham's linked list merge sort algorithm
  75618. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  75619. function sortLinked(list) {
  75620. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  75621. do {
  75622. p = list;
  75623. list = null;
  75624. tail = null;
  75625. numMerges = 0;
  75626. while (p) {
  75627. numMerges++;
  75628. q = p;
  75629. pSize = 0;
  75630. for (i = 0; i < inSize; i++) {
  75631. pSize++;
  75632. q = q.nextZ;
  75633. if (!q)
  75634. break;
  75635. }
  75636. qSize = inSize;
  75637. while (pSize > 0 || (qSize > 0 && q)) {
  75638. if (pSize === 0) {
  75639. e = q;
  75640. q = q.nextZ;
  75641. qSize--;
  75642. }
  75643. else if (qSize === 0 || !q) {
  75644. e = p;
  75645. p = p.nextZ;
  75646. pSize--;
  75647. }
  75648. else if (p.z <= q.z) {
  75649. e = p;
  75650. p = p.nextZ;
  75651. pSize--;
  75652. }
  75653. else {
  75654. e = q;
  75655. q = q.nextZ;
  75656. qSize--;
  75657. }
  75658. if (tail)
  75659. tail.nextZ = e;
  75660. else
  75661. list = e;
  75662. e.prevZ = tail;
  75663. tail = e;
  75664. }
  75665. p = q;
  75666. }
  75667. tail.nextZ = null;
  75668. inSize *= 2;
  75669. } while (numMerges > 1);
  75670. return list;
  75671. }
  75672. // z-order of a point given coords and size of the data bounding box
  75673. function zOrder(x, y, minX, minY, size) {
  75674. // coords are transformed into non-negative 15-bit integer range
  75675. x = 32767 * (x - minX) / size;
  75676. y = 32767 * (y - minY) / size;
  75677. x = (x | (x << 8)) & 0x00FF00FF;
  75678. x = (x | (x << 4)) & 0x0F0F0F0F;
  75679. x = (x | (x << 2)) & 0x33333333;
  75680. x = (x | (x << 1)) & 0x55555555;
  75681. y = (y | (y << 8)) & 0x00FF00FF;
  75682. y = (y | (y << 4)) & 0x0F0F0F0F;
  75683. y = (y | (y << 2)) & 0x33333333;
  75684. y = (y | (y << 1)) & 0x55555555;
  75685. return x | (y << 1);
  75686. }
  75687. // find the leftmost node of a polygon ring
  75688. function getLeftmost(start) {
  75689. var p = start, leftmost = start;
  75690. do {
  75691. if (p.x < leftmost.x)
  75692. leftmost = p;
  75693. p = p.next;
  75694. } while (p !== start);
  75695. return leftmost;
  75696. }
  75697. // check if a point lies within a convex triangle
  75698. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  75699. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  75700. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  75701. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  75702. }
  75703. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  75704. function isValidDiagonal(a, b) {
  75705. return a.next.i !== b.i &&
  75706. a.prev.i !== b.i &&
  75707. !intersectsPolygon(a, b) &&
  75708. locallyInside(a, b) &&
  75709. locallyInside(b, a) &&
  75710. middleInside(a, b);
  75711. }
  75712. // signed area of a triangle
  75713. function area(p, q, r) {
  75714. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  75715. }
  75716. // check if two points are equal
  75717. function equals(p1, p2) {
  75718. return p1.x === p2.x && p1.y === p2.y;
  75719. }
  75720. // check if two segments intersect
  75721. function intersects(p1, q1, p2, q2) {
  75722. if ((equals(p1, q1) && equals(p2, q2)) ||
  75723. (equals(p1, q2) && equals(p2, q1)))
  75724. return true;
  75725. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  75726. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  75727. }
  75728. // check if a polygon diagonal intersects any polygon segments
  75729. function intersectsPolygon(a, b) {
  75730. var p = a;
  75731. do {
  75732. if (p.i !== a.i &&
  75733. p.next.i !== a.i &&
  75734. p.i !== b.i &&
  75735. p.next.i !== b.i &&
  75736. intersects(p, p.next, a, b))
  75737. return true;
  75738. p = p.next;
  75739. } while (p !== a);
  75740. return false;
  75741. }
  75742. // check if a polygon diagonal is locally inside the polygon
  75743. function locallyInside(a, b) {
  75744. return area(a.prev, a, a.next) < 0
  75745. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  75746. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  75747. }
  75748. // check if the middle point of a polygon diagonal is inside the polygon
  75749. function middleInside(a, b) {
  75750. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  75751. do {
  75752. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  75753. inside = !inside;
  75754. p = p.next;
  75755. } while (p !== a);
  75756. return inside;
  75757. }
  75758. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  75759. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  75760. function splitPolygon(a, b) {
  75761. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  75762. a.next = b;
  75763. b.prev = a;
  75764. a2.next = an;
  75765. an.prev = a2;
  75766. b2.next = a2;
  75767. a2.prev = b2;
  75768. bp.next = b2;
  75769. b2.prev = bp;
  75770. return b2;
  75771. }
  75772. // create a node and optionally link it with previous one (in a circular doubly linked list)
  75773. function insertNode(i, x, y, last) {
  75774. var p = new Node(i, x, y);
  75775. if (!last) {
  75776. p.prev = p;
  75777. p.next = p;
  75778. }
  75779. else {
  75780. p.next = last.next;
  75781. p.prev = last;
  75782. last.next.prev = p;
  75783. last.next = p;
  75784. }
  75785. return p;
  75786. }
  75787. function removeNode(p) {
  75788. p.next.prev = p.prev;
  75789. p.prev.next = p.next;
  75790. if (p.prevZ)
  75791. p.prevZ.nextZ = p.nextZ;
  75792. if (p.nextZ)
  75793. p.nextZ.prevZ = p.prevZ;
  75794. }
  75795. /**
  75796. * return a percentage difference between the polygon area and its triangulation area;
  75797. * used to verify correctness of triangulation
  75798. */
  75799. function deviation(data, holeIndices, dim, triangles) {
  75800. var hasHoles = holeIndices && holeIndices.length;
  75801. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  75802. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  75803. if (hasHoles) {
  75804. for (var i = 0, len = holeIndices.length; i < len; i++) {
  75805. var start = holeIndices[i] * dim;
  75806. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75807. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  75808. }
  75809. }
  75810. var trianglesArea = 0;
  75811. for (i = 0; i < triangles.length; i += 3) {
  75812. var a = triangles[i] * dim;
  75813. var b = triangles[i + 1] * dim;
  75814. var c = triangles[i + 2] * dim;
  75815. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  75816. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  75817. }
  75818. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  75819. }
  75820. Earcut.deviation = deviation;
  75821. ;
  75822. function signedArea(data, start, end, dim) {
  75823. var sum = 0;
  75824. for (var i = start, j = end - dim; i < end; i += dim) {
  75825. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  75826. j = i;
  75827. }
  75828. return sum;
  75829. }
  75830. /**
  75831. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  75832. */
  75833. function flatten(data) {
  75834. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  75835. for (var i = 0; i < data.length; i++) {
  75836. for (var j = 0; j < data[i].length; j++) {
  75837. for (var d = 0; d < dim; d++)
  75838. result.vertices.push(data[i][j][d]);
  75839. }
  75840. if (i > 0) {
  75841. holeIndex += data[i - 1].length;
  75842. result.holes.push(holeIndex);
  75843. }
  75844. }
  75845. return result;
  75846. }
  75847. Earcut.flatten = flatten;
  75848. ;
  75849. })(Earcut || (Earcut = {}));
  75850. //# sourceMappingURL=babylon.earcut.js.map
  75851. "use strict";
  75852. var BABYLON;
  75853. (function (BABYLON) {
  75854. var IndexedVector2 = /** @class */ (function (_super) {
  75855. __extends(IndexedVector2, _super);
  75856. function IndexedVector2(original, index) {
  75857. var _this = _super.call(this, original.x, original.y) || this;
  75858. _this.index = index;
  75859. return _this;
  75860. }
  75861. return IndexedVector2;
  75862. }(BABYLON.Vector2));
  75863. var PolygonPoints = /** @class */ (function () {
  75864. function PolygonPoints() {
  75865. this.elements = new Array();
  75866. }
  75867. PolygonPoints.prototype.add = function (originalPoints) {
  75868. var _this = this;
  75869. var result = new Array();
  75870. originalPoints.forEach(function (point) {
  75871. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75872. var newPoint = new IndexedVector2(point, _this.elements.length);
  75873. result.push(newPoint);
  75874. _this.elements.push(newPoint);
  75875. }
  75876. });
  75877. return result;
  75878. };
  75879. PolygonPoints.prototype.computeBounds = function () {
  75880. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75881. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75882. this.elements.forEach(function (point) {
  75883. // x
  75884. if (point.x < lmin.x) {
  75885. lmin.x = point.x;
  75886. }
  75887. else if (point.x > lmax.x) {
  75888. lmax.x = point.x;
  75889. }
  75890. // y
  75891. if (point.y < lmin.y) {
  75892. lmin.y = point.y;
  75893. }
  75894. else if (point.y > lmax.y) {
  75895. lmax.y = point.y;
  75896. }
  75897. });
  75898. return {
  75899. min: lmin,
  75900. max: lmax,
  75901. width: lmax.x - lmin.x,
  75902. height: lmax.y - lmin.y
  75903. };
  75904. };
  75905. return PolygonPoints;
  75906. }());
  75907. var Polygon = /** @class */ (function () {
  75908. function Polygon() {
  75909. }
  75910. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75911. return [
  75912. new BABYLON.Vector2(xmin, ymin),
  75913. new BABYLON.Vector2(xmax, ymin),
  75914. new BABYLON.Vector2(xmax, ymax),
  75915. new BABYLON.Vector2(xmin, ymax)
  75916. ];
  75917. };
  75918. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75919. if (cx === void 0) { cx = 0; }
  75920. if (cy === void 0) { cy = 0; }
  75921. if (numberOfSides === void 0) { numberOfSides = 32; }
  75922. var result = new Array();
  75923. var angle = 0;
  75924. var increment = (Math.PI * 2) / numberOfSides;
  75925. for (var i = 0; i < numberOfSides; i++) {
  75926. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75927. angle -= increment;
  75928. }
  75929. return result;
  75930. };
  75931. Polygon.Parse = function (input) {
  75932. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75933. var i, result = [];
  75934. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75935. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75936. }
  75937. return result;
  75938. };
  75939. Polygon.StartingAt = function (x, y) {
  75940. return BABYLON.Path2.StartingAt(x, y);
  75941. };
  75942. return Polygon;
  75943. }());
  75944. BABYLON.Polygon = Polygon;
  75945. var PolygonMeshBuilder = /** @class */ (function () {
  75946. function PolygonMeshBuilder(name, contours, scene) {
  75947. this._points = new PolygonPoints();
  75948. this._outlinepoints = new PolygonPoints();
  75949. this._holes = new Array();
  75950. this._epoints = new Array();
  75951. this._eholes = new Array();
  75952. this._name = name;
  75953. this._scene = scene;
  75954. var points;
  75955. if (contours instanceof BABYLON.Path2) {
  75956. points = contours.getPoints();
  75957. }
  75958. else {
  75959. points = contours;
  75960. }
  75961. this._addToepoint(points);
  75962. this._points.add(points);
  75963. this._outlinepoints.add(points);
  75964. }
  75965. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75966. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75967. var p = points_1[_i];
  75968. this._epoints.push(p.x, p.y);
  75969. }
  75970. };
  75971. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75972. this._points.add(hole);
  75973. var holepoints = new PolygonPoints();
  75974. holepoints.add(hole);
  75975. this._holes.push(holepoints);
  75976. this._eholes.push(this._epoints.length / 2);
  75977. this._addToepoint(hole);
  75978. return this;
  75979. };
  75980. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75981. var _this = this;
  75982. if (updatable === void 0) { updatable = false; }
  75983. if (depth === void 0) { depth = 0; }
  75984. var result = new BABYLON.Mesh(this._name, this._scene);
  75985. var normals = new Array();
  75986. var positions = new Array();
  75987. var uvs = new Array();
  75988. var bounds = this._points.computeBounds();
  75989. this._points.elements.forEach(function (p) {
  75990. normals.push(0, 1.0, 0);
  75991. positions.push(p.x, 0, p.y);
  75992. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75993. });
  75994. var indices = new Array();
  75995. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75996. for (var i = 0; i < res.length; i++) {
  75997. indices.push(res[i]);
  75998. }
  75999. if (depth > 0) {
  76000. var positionscount = (positions.length / 3); //get the current pointcount
  76001. this._points.elements.forEach(function (p) {
  76002. normals.push(0, -1.0, 0);
  76003. positions.push(p.x, -depth, p.y);
  76004. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  76005. });
  76006. var totalCount = indices.length;
  76007. for (var i = 0; i < totalCount; i += 3) {
  76008. var i0 = indices[i + 0];
  76009. var i1 = indices[i + 1];
  76010. var i2 = indices[i + 2];
  76011. indices.push(i2 + positionscount);
  76012. indices.push(i1 + positionscount);
  76013. indices.push(i0 + positionscount);
  76014. }
  76015. //Add the sides
  76016. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  76017. this._holes.forEach(function (hole) {
  76018. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  76019. });
  76020. }
  76021. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  76022. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  76023. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  76024. result.setIndices(indices);
  76025. return result;
  76026. };
  76027. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  76028. var StartIndex = positions.length / 3;
  76029. var ulength = 0;
  76030. for (var i = 0; i < points.elements.length; i++) {
  76031. var p = points.elements[i];
  76032. var p1;
  76033. if ((i + 1) > points.elements.length - 1) {
  76034. p1 = points.elements[0];
  76035. }
  76036. else {
  76037. p1 = points.elements[i + 1];
  76038. }
  76039. positions.push(p.x, 0, p.y);
  76040. positions.push(p.x, -depth, p.y);
  76041. positions.push(p1.x, 0, p1.y);
  76042. positions.push(p1.x, -depth, p1.y);
  76043. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76044. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76045. var v3 = v2.subtract(v1);
  76046. var v4 = new BABYLON.Vector3(0, 1, 0);
  76047. var vn = BABYLON.Vector3.Cross(v3, v4);
  76048. vn = vn.normalize();
  76049. uvs.push(ulength / bounds.width, 0);
  76050. uvs.push(ulength / bounds.width, 1);
  76051. ulength += v3.length();
  76052. uvs.push((ulength / bounds.width), 0);
  76053. uvs.push((ulength / bounds.width), 1);
  76054. if (!flip) {
  76055. normals.push(-vn.x, -vn.y, -vn.z);
  76056. normals.push(-vn.x, -vn.y, -vn.z);
  76057. normals.push(-vn.x, -vn.y, -vn.z);
  76058. normals.push(-vn.x, -vn.y, -vn.z);
  76059. indices.push(StartIndex);
  76060. indices.push(StartIndex + 1);
  76061. indices.push(StartIndex + 2);
  76062. indices.push(StartIndex + 1);
  76063. indices.push(StartIndex + 3);
  76064. indices.push(StartIndex + 2);
  76065. }
  76066. else {
  76067. normals.push(vn.x, vn.y, vn.z);
  76068. normals.push(vn.x, vn.y, vn.z);
  76069. normals.push(vn.x, vn.y, vn.z);
  76070. normals.push(vn.x, vn.y, vn.z);
  76071. indices.push(StartIndex);
  76072. indices.push(StartIndex + 2);
  76073. indices.push(StartIndex + 1);
  76074. indices.push(StartIndex + 1);
  76075. indices.push(StartIndex + 2);
  76076. indices.push(StartIndex + 3);
  76077. }
  76078. StartIndex += 4;
  76079. }
  76080. ;
  76081. };
  76082. return PolygonMeshBuilder;
  76083. }());
  76084. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76085. })(BABYLON || (BABYLON = {}));
  76086. //# sourceMappingURL=babylon.polygonMesh.js.map
  76087. "use strict";
  76088. var BABYLON;
  76089. (function (BABYLON) {
  76090. // Unique ID when we import meshes from Babylon to CSG
  76091. var currentCSGMeshId = 0;
  76092. // # class Vertex
  76093. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76094. // one to provide additional features like texture coordinates and vertex
  76095. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76096. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76097. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76098. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76099. // is not used anywhere else.
  76100. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76101. var Vertex = /** @class */ (function () {
  76102. function Vertex(pos, normal, uv) {
  76103. this.pos = pos;
  76104. this.normal = normal;
  76105. this.uv = uv;
  76106. }
  76107. Vertex.prototype.clone = function () {
  76108. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76109. };
  76110. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76111. // orientation of a polygon is flipped.
  76112. Vertex.prototype.flip = function () {
  76113. this.normal = this.normal.scale(-1);
  76114. };
  76115. // Create a new vertex between this vertex and `other` by linearly
  76116. // interpolating all properties using a parameter of `t`. Subclasses should
  76117. // override this to interpolate additional properties.
  76118. Vertex.prototype.interpolate = function (other, t) {
  76119. 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));
  76120. };
  76121. return Vertex;
  76122. }());
  76123. // # class Plane
  76124. // Represents a plane in 3D space.
  76125. var Plane = /** @class */ (function () {
  76126. function Plane(normal, w) {
  76127. this.normal = normal;
  76128. this.w = w;
  76129. }
  76130. Plane.FromPoints = function (a, b, c) {
  76131. var v0 = c.subtract(a);
  76132. var v1 = b.subtract(a);
  76133. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76134. return null;
  76135. }
  76136. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76137. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76138. };
  76139. Plane.prototype.clone = function () {
  76140. return new Plane(this.normal.clone(), this.w);
  76141. };
  76142. Plane.prototype.flip = function () {
  76143. this.normal.scaleInPlace(-1);
  76144. this.w = -this.w;
  76145. };
  76146. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76147. // fragments in the appropriate lists. Coplanar polygons go into either
  76148. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76149. // respect to this plane. Polygons in front or in back of this plane go into
  76150. // either `front` or `back`.
  76151. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76152. var COPLANAR = 0;
  76153. var FRONT = 1;
  76154. var BACK = 2;
  76155. var SPANNING = 3;
  76156. // Classify each point as well as the entire polygon into one of the above
  76157. // four classes.
  76158. var polygonType = 0;
  76159. var types = [];
  76160. var i;
  76161. var t;
  76162. for (i = 0; i < polygon.vertices.length; i++) {
  76163. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76164. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76165. polygonType |= type;
  76166. types.push(type);
  76167. }
  76168. // Put the polygon in the correct list, splitting it when necessary.
  76169. switch (polygonType) {
  76170. case COPLANAR:
  76171. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76172. break;
  76173. case FRONT:
  76174. front.push(polygon);
  76175. break;
  76176. case BACK:
  76177. back.push(polygon);
  76178. break;
  76179. case SPANNING:
  76180. var f = [], b = [];
  76181. for (i = 0; i < polygon.vertices.length; i++) {
  76182. var j = (i + 1) % polygon.vertices.length;
  76183. var ti = types[i], tj = types[j];
  76184. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76185. if (ti !== BACK)
  76186. f.push(vi);
  76187. if (ti !== FRONT)
  76188. b.push(ti !== BACK ? vi.clone() : vi);
  76189. if ((ti | tj) === SPANNING) {
  76190. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76191. var v = vi.interpolate(vj, t);
  76192. f.push(v);
  76193. b.push(v.clone());
  76194. }
  76195. }
  76196. var poly;
  76197. if (f.length >= 3) {
  76198. poly = new Polygon(f, polygon.shared);
  76199. if (poly.plane)
  76200. front.push(poly);
  76201. }
  76202. if (b.length >= 3) {
  76203. poly = new Polygon(b, polygon.shared);
  76204. if (poly.plane)
  76205. back.push(poly);
  76206. }
  76207. break;
  76208. }
  76209. };
  76210. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76211. // point is on the plane.
  76212. Plane.EPSILON = 1e-5;
  76213. return Plane;
  76214. }());
  76215. // # class Polygon
  76216. // Represents a convex polygon. The vertices used to initialize a polygon must
  76217. // be coplanar and form a convex loop.
  76218. //
  76219. // Each convex polygon has a `shared` property, which is shared between all
  76220. // polygons that are clones of each other or were split from the same polygon.
  76221. // This can be used to define per-polygon properties (such as surface color).
  76222. var Polygon = /** @class */ (function () {
  76223. function Polygon(vertices, shared) {
  76224. this.vertices = vertices;
  76225. this.shared = shared;
  76226. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76227. }
  76228. Polygon.prototype.clone = function () {
  76229. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76230. return new Polygon(vertices, this.shared);
  76231. };
  76232. Polygon.prototype.flip = function () {
  76233. this.vertices.reverse().map(function (v) { v.flip(); });
  76234. this.plane.flip();
  76235. };
  76236. return Polygon;
  76237. }());
  76238. // # class Node
  76239. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76240. // by picking a polygon to split along. That polygon (and all other coplanar
  76241. // polygons) are added directly to that node and the other polygons are added to
  76242. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76243. // no distinction between internal and leaf nodes.
  76244. var Node = /** @class */ (function () {
  76245. function Node(polygons) {
  76246. this.plane = null;
  76247. this.front = null;
  76248. this.back = null;
  76249. this.polygons = new Array();
  76250. if (polygons) {
  76251. this.build(polygons);
  76252. }
  76253. }
  76254. Node.prototype.clone = function () {
  76255. var node = new Node();
  76256. node.plane = this.plane && this.plane.clone();
  76257. node.front = this.front && this.front.clone();
  76258. node.back = this.back && this.back.clone();
  76259. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76260. return node;
  76261. };
  76262. // Convert solid space to empty space and empty space to solid space.
  76263. Node.prototype.invert = function () {
  76264. for (var i = 0; i < this.polygons.length; i++) {
  76265. this.polygons[i].flip();
  76266. }
  76267. if (this.plane) {
  76268. this.plane.flip();
  76269. }
  76270. if (this.front) {
  76271. this.front.invert();
  76272. }
  76273. if (this.back) {
  76274. this.back.invert();
  76275. }
  76276. var temp = this.front;
  76277. this.front = this.back;
  76278. this.back = temp;
  76279. };
  76280. // Recursively remove all polygons in `polygons` that are inside this BSP
  76281. // tree.
  76282. Node.prototype.clipPolygons = function (polygons) {
  76283. if (!this.plane)
  76284. return polygons.slice();
  76285. var front = new Array(), back = new Array();
  76286. for (var i = 0; i < polygons.length; i++) {
  76287. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76288. }
  76289. if (this.front) {
  76290. front = this.front.clipPolygons(front);
  76291. }
  76292. if (this.back) {
  76293. back = this.back.clipPolygons(back);
  76294. }
  76295. else {
  76296. back = [];
  76297. }
  76298. return front.concat(back);
  76299. };
  76300. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76301. // `bsp`.
  76302. Node.prototype.clipTo = function (bsp) {
  76303. this.polygons = bsp.clipPolygons(this.polygons);
  76304. if (this.front)
  76305. this.front.clipTo(bsp);
  76306. if (this.back)
  76307. this.back.clipTo(bsp);
  76308. };
  76309. // Return a list of all polygons in this BSP tree.
  76310. Node.prototype.allPolygons = function () {
  76311. var polygons = this.polygons.slice();
  76312. if (this.front)
  76313. polygons = polygons.concat(this.front.allPolygons());
  76314. if (this.back)
  76315. polygons = polygons.concat(this.back.allPolygons());
  76316. return polygons;
  76317. };
  76318. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76319. // new polygons are filtered down to the bottom of the tree and become new
  76320. // nodes there. Each set of polygons is partitioned using the first polygon
  76321. // (no heuristic is used to pick a good split).
  76322. Node.prototype.build = function (polygons) {
  76323. if (!polygons.length)
  76324. return;
  76325. if (!this.plane)
  76326. this.plane = polygons[0].plane.clone();
  76327. var front = new Array(), back = new Array();
  76328. for (var i = 0; i < polygons.length; i++) {
  76329. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76330. }
  76331. if (front.length) {
  76332. if (!this.front)
  76333. this.front = new Node();
  76334. this.front.build(front);
  76335. }
  76336. if (back.length) {
  76337. if (!this.back)
  76338. this.back = new Node();
  76339. this.back.build(back);
  76340. }
  76341. };
  76342. return Node;
  76343. }());
  76344. var CSG = /** @class */ (function () {
  76345. function CSG() {
  76346. this.polygons = new Array();
  76347. }
  76348. // Convert BABYLON.Mesh to BABYLON.CSG
  76349. CSG.FromMesh = function (mesh) {
  76350. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76351. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76352. if (mesh instanceof BABYLON.Mesh) {
  76353. mesh.computeWorldMatrix(true);
  76354. matrix = mesh.getWorldMatrix();
  76355. meshPosition = mesh.position.clone();
  76356. meshRotation = mesh.rotation.clone();
  76357. if (mesh.rotationQuaternion) {
  76358. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76359. }
  76360. meshScaling = mesh.scaling.clone();
  76361. }
  76362. else {
  76363. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76364. }
  76365. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76366. var subMeshes = mesh.subMeshes;
  76367. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76368. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76369. vertices = [];
  76370. for (var j = 0; j < 3; j++) {
  76371. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76372. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76373. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76374. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76375. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76376. vertex = new Vertex(position, normal, uv);
  76377. vertices.push(vertex);
  76378. }
  76379. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76380. // To handle the case of degenerated triangle
  76381. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76382. if (polygon.plane)
  76383. polygons.push(polygon);
  76384. }
  76385. }
  76386. var csg = CSG.FromPolygons(polygons);
  76387. csg.matrix = matrix;
  76388. csg.position = meshPosition;
  76389. csg.rotation = meshRotation;
  76390. csg.scaling = meshScaling;
  76391. csg.rotationQuaternion = meshRotationQuaternion;
  76392. currentCSGMeshId++;
  76393. return csg;
  76394. };
  76395. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76396. CSG.FromPolygons = function (polygons) {
  76397. var csg = new CSG();
  76398. csg.polygons = polygons;
  76399. return csg;
  76400. };
  76401. CSG.prototype.clone = function () {
  76402. var csg = new CSG();
  76403. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76404. csg.copyTransformAttributes(this);
  76405. return csg;
  76406. };
  76407. CSG.prototype.union = function (csg) {
  76408. var a = new Node(this.clone().polygons);
  76409. var b = new Node(csg.clone().polygons);
  76410. a.clipTo(b);
  76411. b.clipTo(a);
  76412. b.invert();
  76413. b.clipTo(a);
  76414. b.invert();
  76415. a.build(b.allPolygons());
  76416. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76417. };
  76418. CSG.prototype.unionInPlace = function (csg) {
  76419. var a = new Node(this.polygons);
  76420. var b = new Node(csg.polygons);
  76421. a.clipTo(b);
  76422. b.clipTo(a);
  76423. b.invert();
  76424. b.clipTo(a);
  76425. b.invert();
  76426. a.build(b.allPolygons());
  76427. this.polygons = a.allPolygons();
  76428. };
  76429. CSG.prototype.subtract = function (csg) {
  76430. var a = new Node(this.clone().polygons);
  76431. var b = new Node(csg.clone().polygons);
  76432. a.invert();
  76433. a.clipTo(b);
  76434. b.clipTo(a);
  76435. b.invert();
  76436. b.clipTo(a);
  76437. b.invert();
  76438. a.build(b.allPolygons());
  76439. a.invert();
  76440. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76441. };
  76442. CSG.prototype.subtractInPlace = function (csg) {
  76443. var a = new Node(this.polygons);
  76444. var b = new Node(csg.polygons);
  76445. a.invert();
  76446. a.clipTo(b);
  76447. b.clipTo(a);
  76448. b.invert();
  76449. b.clipTo(a);
  76450. b.invert();
  76451. a.build(b.allPolygons());
  76452. a.invert();
  76453. this.polygons = a.allPolygons();
  76454. };
  76455. CSG.prototype.intersect = function (csg) {
  76456. var a = new Node(this.clone().polygons);
  76457. var b = new Node(csg.clone().polygons);
  76458. a.invert();
  76459. b.clipTo(a);
  76460. b.invert();
  76461. a.clipTo(b);
  76462. b.clipTo(a);
  76463. a.build(b.allPolygons());
  76464. a.invert();
  76465. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76466. };
  76467. CSG.prototype.intersectInPlace = function (csg) {
  76468. var a = new Node(this.polygons);
  76469. var b = new Node(csg.polygons);
  76470. a.invert();
  76471. b.clipTo(a);
  76472. b.invert();
  76473. a.clipTo(b);
  76474. b.clipTo(a);
  76475. a.build(b.allPolygons());
  76476. a.invert();
  76477. this.polygons = a.allPolygons();
  76478. };
  76479. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76480. // not modified.
  76481. CSG.prototype.inverse = function () {
  76482. var csg = this.clone();
  76483. csg.inverseInPlace();
  76484. return csg;
  76485. };
  76486. CSG.prototype.inverseInPlace = function () {
  76487. this.polygons.map(function (p) { p.flip(); });
  76488. };
  76489. // This is used to keep meshes transformations so they can be restored
  76490. // when we build back a Babylon Mesh
  76491. // NB : All CSG operations are performed in world coordinates
  76492. CSG.prototype.copyTransformAttributes = function (csg) {
  76493. this.matrix = csg.matrix;
  76494. this.position = csg.position;
  76495. this.rotation = csg.rotation;
  76496. this.scaling = csg.scaling;
  76497. this.rotationQuaternion = csg.rotationQuaternion;
  76498. return this;
  76499. };
  76500. // Build Raw mesh from CSG
  76501. // Coordinates here are in world space
  76502. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76503. var matrix = this.matrix.clone();
  76504. matrix.invert();
  76505. 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;
  76506. if (keepSubMeshes) {
  76507. // Sort Polygons, since subMeshes are indices range
  76508. polygons.sort(function (a, b) {
  76509. if (a.shared.meshId === b.shared.meshId) {
  76510. return a.shared.subMeshId - b.shared.subMeshId;
  76511. }
  76512. else {
  76513. return a.shared.meshId - b.shared.meshId;
  76514. }
  76515. });
  76516. }
  76517. for (var i = 0, il = polygons.length; i < il; i++) {
  76518. polygon = polygons[i];
  76519. // Building SubMeshes
  76520. if (!subMesh_dict[polygon.shared.meshId]) {
  76521. subMesh_dict[polygon.shared.meshId] = {};
  76522. }
  76523. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76524. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76525. indexStart: +Infinity,
  76526. indexEnd: -Infinity,
  76527. materialIndex: polygon.shared.materialIndex
  76528. };
  76529. }
  76530. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76531. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76532. polygonIndices[0] = 0;
  76533. polygonIndices[1] = j - 1;
  76534. polygonIndices[2] = j;
  76535. for (var k = 0; k < 3; k++) {
  76536. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76537. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76538. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76539. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76540. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76541. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76542. // Check if 2 points can be merged
  76543. if (!(typeof vertex_idx !== 'undefined' &&
  76544. normals[vertex_idx * 3] === localNormal.x &&
  76545. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76546. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76547. uvs[vertex_idx * 2] === uv.x &&
  76548. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76549. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76550. uvs.push(uv.x, uv.y);
  76551. normals.push(normal.x, normal.y, normal.z);
  76552. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76553. }
  76554. indices.push(vertex_idx);
  76555. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76556. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76557. currentIndex++;
  76558. }
  76559. }
  76560. }
  76561. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76562. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76563. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76564. mesh.setIndices(indices, null);
  76565. if (keepSubMeshes) {
  76566. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76567. var materialIndexOffset = 0, materialMaxIndex;
  76568. mesh.subMeshes = new Array();
  76569. for (var m in subMesh_dict) {
  76570. materialMaxIndex = -1;
  76571. for (var sm in subMesh_dict[m]) {
  76572. subMesh_obj = subMesh_dict[m][sm];
  76573. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76574. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76575. }
  76576. materialIndexOffset += ++materialMaxIndex;
  76577. }
  76578. }
  76579. return mesh;
  76580. };
  76581. // Build Mesh from CSG taking material and transforms into account
  76582. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76583. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76584. mesh.material = material;
  76585. mesh.position.copyFrom(this.position);
  76586. mesh.rotation.copyFrom(this.rotation);
  76587. if (this.rotationQuaternion) {
  76588. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76589. }
  76590. mesh.scaling.copyFrom(this.scaling);
  76591. mesh.computeWorldMatrix(true);
  76592. return mesh;
  76593. };
  76594. return CSG;
  76595. }());
  76596. BABYLON.CSG = CSG;
  76597. })(BABYLON || (BABYLON = {}));
  76598. //# sourceMappingURL=babylon.csg.js.map
  76599. "use strict";
  76600. var BABYLON;
  76601. (function (BABYLON) {
  76602. var LensFlare = /** @class */ (function () {
  76603. function LensFlare(size, position, color, imgUrl, system) {
  76604. this.size = size;
  76605. this.position = position;
  76606. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76607. this.color = color || new BABYLON.Color3(1, 1, 1);
  76608. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76609. this._system = system;
  76610. system.lensFlares.push(this);
  76611. }
  76612. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76613. return new LensFlare(size, position, color, imgUrl, system);
  76614. };
  76615. LensFlare.prototype.dispose = function () {
  76616. if (this.texture) {
  76617. this.texture.dispose();
  76618. }
  76619. // Remove from scene
  76620. var index = this._system.lensFlares.indexOf(this);
  76621. this._system.lensFlares.splice(index, 1);
  76622. };
  76623. ;
  76624. return LensFlare;
  76625. }());
  76626. BABYLON.LensFlare = LensFlare;
  76627. })(BABYLON || (BABYLON = {}));
  76628. //# sourceMappingURL=babylon.lensFlare.js.map
  76629. "use strict";
  76630. var BABYLON;
  76631. (function (BABYLON) {
  76632. var LensFlareSystem = /** @class */ (function () {
  76633. function LensFlareSystem(name, emitter, scene) {
  76634. this.name = name;
  76635. this.lensFlares = new Array();
  76636. this.borderLimit = 300;
  76637. this.viewportBorder = 0;
  76638. this.layerMask = 0x0FFFFFFF;
  76639. this._vertexBuffers = {};
  76640. this._isEnabled = true;
  76641. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76642. this._emitter = emitter;
  76643. this.id = name;
  76644. scene.lensFlareSystems.push(this);
  76645. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76646. var engine = scene.getEngine();
  76647. // VBO
  76648. var vertices = [];
  76649. vertices.push(1, 1);
  76650. vertices.push(-1, 1);
  76651. vertices.push(-1, -1);
  76652. vertices.push(1, -1);
  76653. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76654. // Indices
  76655. var indices = [];
  76656. indices.push(0);
  76657. indices.push(1);
  76658. indices.push(2);
  76659. indices.push(0);
  76660. indices.push(2);
  76661. indices.push(3);
  76662. this._indexBuffer = engine.createIndexBuffer(indices);
  76663. // Effects
  76664. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76665. }
  76666. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76667. get: function () {
  76668. return this._isEnabled;
  76669. },
  76670. set: function (value) {
  76671. this._isEnabled = value;
  76672. },
  76673. enumerable: true,
  76674. configurable: true
  76675. });
  76676. LensFlareSystem.prototype.getScene = function () {
  76677. return this._scene;
  76678. };
  76679. LensFlareSystem.prototype.getEmitter = function () {
  76680. return this._emitter;
  76681. };
  76682. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76683. this._emitter = newEmitter;
  76684. };
  76685. LensFlareSystem.prototype.getEmitterPosition = function () {
  76686. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76687. };
  76688. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76689. var position = this.getEmitterPosition();
  76690. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76691. this._positionX = position.x;
  76692. this._positionY = position.y;
  76693. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76694. if (this.viewportBorder > 0) {
  76695. globalViewport.x -= this.viewportBorder;
  76696. globalViewport.y -= this.viewportBorder;
  76697. globalViewport.width += this.viewportBorder * 2;
  76698. globalViewport.height += this.viewportBorder * 2;
  76699. position.x += this.viewportBorder;
  76700. position.y += this.viewportBorder;
  76701. this._positionX += this.viewportBorder;
  76702. this._positionY += this.viewportBorder;
  76703. }
  76704. if (position.z > 0) {
  76705. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  76706. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76707. return true;
  76708. }
  76709. return true;
  76710. }
  76711. return false;
  76712. };
  76713. LensFlareSystem.prototype._isVisible = function () {
  76714. if (!this._isEnabled || !this._scene.activeCamera) {
  76715. return false;
  76716. }
  76717. var emitterPosition = this.getEmitterPosition();
  76718. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  76719. var distance = direction.length();
  76720. direction.normalize();
  76721. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  76722. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  76723. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  76724. };
  76725. LensFlareSystem.prototype.render = function () {
  76726. if (!this._effect.isReady() || !this._scene.activeCamera)
  76727. return false;
  76728. var engine = this._scene.getEngine();
  76729. var viewport = this._scene.activeCamera.viewport;
  76730. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  76731. // Position
  76732. if (!this.computeEffectivePosition(globalViewport)) {
  76733. return false;
  76734. }
  76735. // Visibility
  76736. if (!this._isVisible()) {
  76737. return false;
  76738. }
  76739. // Intensity
  76740. var awayX;
  76741. var awayY;
  76742. if (this._positionX < this.borderLimit + globalViewport.x) {
  76743. awayX = this.borderLimit + globalViewport.x - this._positionX;
  76744. }
  76745. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  76746. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  76747. }
  76748. else {
  76749. awayX = 0;
  76750. }
  76751. if (this._positionY < this.borderLimit + globalViewport.y) {
  76752. awayY = this.borderLimit + globalViewport.y - this._positionY;
  76753. }
  76754. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  76755. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  76756. }
  76757. else {
  76758. awayY = 0;
  76759. }
  76760. var away = (awayX > awayY) ? awayX : awayY;
  76761. away -= this.viewportBorder;
  76762. if (away > this.borderLimit) {
  76763. away = this.borderLimit;
  76764. }
  76765. var intensity = 1.0 - (away / this.borderLimit);
  76766. if (intensity < 0) {
  76767. return false;
  76768. }
  76769. if (intensity > 1.0) {
  76770. intensity = 1.0;
  76771. }
  76772. if (this.viewportBorder > 0) {
  76773. globalViewport.x += this.viewportBorder;
  76774. globalViewport.y += this.viewportBorder;
  76775. globalViewport.width -= this.viewportBorder * 2;
  76776. globalViewport.height -= this.viewportBorder * 2;
  76777. this._positionX -= this.viewportBorder;
  76778. this._positionY -= this.viewportBorder;
  76779. }
  76780. // Position
  76781. var centerX = globalViewport.x + globalViewport.width / 2;
  76782. var centerY = globalViewport.y + globalViewport.height / 2;
  76783. var distX = centerX - this._positionX;
  76784. var distY = centerY - this._positionY;
  76785. // Effects
  76786. engine.enableEffect(this._effect);
  76787. engine.setState(false);
  76788. engine.setDepthBuffer(false);
  76789. // VBOs
  76790. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76791. // Flares
  76792. for (var index = 0; index < this.lensFlares.length; index++) {
  76793. var flare = this.lensFlares[index];
  76794. engine.setAlphaMode(flare.alphaMode);
  76795. var x = centerX - (distX * flare.position);
  76796. var y = centerY - (distY * flare.position);
  76797. var cw = flare.size;
  76798. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76799. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76800. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76801. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76802. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76803. // Texture
  76804. this._effect.setTexture("textureSampler", flare.texture);
  76805. // Color
  76806. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76807. // Draw order
  76808. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76809. }
  76810. engine.setDepthBuffer(true);
  76811. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76812. return true;
  76813. };
  76814. LensFlareSystem.prototype.dispose = function () {
  76815. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76816. if (vertexBuffer) {
  76817. vertexBuffer.dispose();
  76818. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76819. }
  76820. if (this._indexBuffer) {
  76821. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76822. this._indexBuffer = null;
  76823. }
  76824. while (this.lensFlares.length) {
  76825. this.lensFlares[0].dispose();
  76826. }
  76827. // Remove from scene
  76828. var index = this._scene.lensFlareSystems.indexOf(this);
  76829. this._scene.lensFlareSystems.splice(index, 1);
  76830. };
  76831. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76832. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76833. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76834. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76835. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76836. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76837. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76838. var parsedFlare = parsedLensFlareSystem.flares[index];
  76839. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76840. }
  76841. return lensFlareSystem;
  76842. };
  76843. LensFlareSystem.prototype.serialize = function () {
  76844. var serializationObject = {};
  76845. serializationObject.id = this.id;
  76846. serializationObject.name = this.name;
  76847. serializationObject.emitterId = this.getEmitter().id;
  76848. serializationObject.borderLimit = this.borderLimit;
  76849. serializationObject.flares = [];
  76850. for (var index = 0; index < this.lensFlares.length; index++) {
  76851. var flare = this.lensFlares[index];
  76852. serializationObject.flares.push({
  76853. size: flare.size,
  76854. position: flare.position,
  76855. color: flare.color.asArray(),
  76856. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76857. });
  76858. }
  76859. return serializationObject;
  76860. };
  76861. return LensFlareSystem;
  76862. }());
  76863. BABYLON.LensFlareSystem = LensFlareSystem;
  76864. })(BABYLON || (BABYLON = {}));
  76865. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76866. "use strict";
  76867. var BABYLON;
  76868. (function (BABYLON) {
  76869. /**
  76870. * This is a holder class for the physics joint created by the physics plugin.
  76871. * It holds a set of functions to control the underlying joint.
  76872. */
  76873. var PhysicsJoint = /** @class */ (function () {
  76874. function PhysicsJoint(type, jointData) {
  76875. this.type = type;
  76876. this.jointData = jointData;
  76877. jointData.nativeParams = jointData.nativeParams || {};
  76878. }
  76879. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76880. get: function () {
  76881. return this._physicsJoint;
  76882. },
  76883. set: function (newJoint) {
  76884. if (this._physicsJoint) {
  76885. //remove from the wolrd
  76886. }
  76887. this._physicsJoint = newJoint;
  76888. },
  76889. enumerable: true,
  76890. configurable: true
  76891. });
  76892. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76893. set: function (physicsPlugin) {
  76894. this._physicsPlugin = physicsPlugin;
  76895. },
  76896. enumerable: true,
  76897. configurable: true
  76898. });
  76899. /**
  76900. * Execute a function that is physics-plugin specific.
  76901. * @param {Function} func the function that will be executed.
  76902. * It accepts two parameters: the physics world and the physics joint.
  76903. */
  76904. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76905. func(this._physicsPlugin.world, this._physicsJoint);
  76906. };
  76907. //TODO check if the native joints are the same
  76908. //Joint Types
  76909. PhysicsJoint.DistanceJoint = 0;
  76910. PhysicsJoint.HingeJoint = 1;
  76911. PhysicsJoint.BallAndSocketJoint = 2;
  76912. PhysicsJoint.WheelJoint = 3;
  76913. PhysicsJoint.SliderJoint = 4;
  76914. //OIMO
  76915. PhysicsJoint.PrismaticJoint = 5;
  76916. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76917. PhysicsJoint.UniversalJoint = 6;
  76918. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76919. //Cannon
  76920. //Similar to a Ball-Joint. Different in params
  76921. PhysicsJoint.PointToPointJoint = 8;
  76922. //Cannon only at the moment
  76923. PhysicsJoint.SpringJoint = 9;
  76924. PhysicsJoint.LockJoint = 10;
  76925. return PhysicsJoint;
  76926. }());
  76927. BABYLON.PhysicsJoint = PhysicsJoint;
  76928. /**
  76929. * A class representing a physics distance joint.
  76930. */
  76931. var DistanceJoint = /** @class */ (function (_super) {
  76932. __extends(DistanceJoint, _super);
  76933. function DistanceJoint(jointData) {
  76934. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76935. }
  76936. /**
  76937. * Update the predefined distance.
  76938. */
  76939. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76940. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76941. };
  76942. return DistanceJoint;
  76943. }(PhysicsJoint));
  76944. BABYLON.DistanceJoint = DistanceJoint;
  76945. var MotorEnabledJoint = /** @class */ (function (_super) {
  76946. __extends(MotorEnabledJoint, _super);
  76947. function MotorEnabledJoint(type, jointData) {
  76948. return _super.call(this, type, jointData) || this;
  76949. }
  76950. /**
  76951. * Set the motor values.
  76952. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76953. * @param {number} force the force to apply
  76954. * @param {number} maxForce max force for this motor.
  76955. */
  76956. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76957. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76958. };
  76959. /**
  76960. * Set the motor's limits.
  76961. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76962. */
  76963. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76964. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76965. };
  76966. return MotorEnabledJoint;
  76967. }(PhysicsJoint));
  76968. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76969. /**
  76970. * This class represents a single hinge physics joint
  76971. */
  76972. var HingeJoint = /** @class */ (function (_super) {
  76973. __extends(HingeJoint, _super);
  76974. function HingeJoint(jointData) {
  76975. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76976. }
  76977. /**
  76978. * Set the motor values.
  76979. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76980. * @param {number} force the force to apply
  76981. * @param {number} maxForce max force for this motor.
  76982. */
  76983. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76984. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76985. };
  76986. /**
  76987. * Set the motor's limits.
  76988. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76989. */
  76990. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76991. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76992. };
  76993. return HingeJoint;
  76994. }(MotorEnabledJoint));
  76995. BABYLON.HingeJoint = HingeJoint;
  76996. /**
  76997. * This class represents a dual hinge physics joint (same as wheel joint)
  76998. */
  76999. var Hinge2Joint = /** @class */ (function (_super) {
  77000. __extends(Hinge2Joint, _super);
  77001. function Hinge2Joint(jointData) {
  77002. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  77003. }
  77004. /**
  77005. * Set the motor values.
  77006. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77007. * @param {number} force the force to apply
  77008. * @param {number} maxForce max force for this motor.
  77009. * @param {motorIndex} the motor's index, 0 or 1.
  77010. */
  77011. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  77012. if (motorIndex === void 0) { motorIndex = 0; }
  77013. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  77014. };
  77015. /**
  77016. * Set the motor limits.
  77017. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77018. * @param {number} upperLimit the upper limit
  77019. * @param {number} lowerLimit lower limit
  77020. * @param {motorIndex} the motor's index, 0 or 1.
  77021. */
  77022. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  77023. if (motorIndex === void 0) { motorIndex = 0; }
  77024. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  77025. };
  77026. return Hinge2Joint;
  77027. }(MotorEnabledJoint));
  77028. BABYLON.Hinge2Joint = Hinge2Joint;
  77029. })(BABYLON || (BABYLON = {}));
  77030. //# sourceMappingURL=babylon.physicsJoint.js.map
  77031. "use strict";
  77032. var BABYLON;
  77033. (function (BABYLON) {
  77034. var PhysicsImpostor = /** @class */ (function () {
  77035. function PhysicsImpostor(object, type, _options, _scene) {
  77036. if (_options === void 0) { _options = { mass: 0 }; }
  77037. var _this = this;
  77038. this.object = object;
  77039. this.type = type;
  77040. this._options = _options;
  77041. this._scene = _scene;
  77042. this._bodyUpdateRequired = false;
  77043. this._onBeforePhysicsStepCallbacks = new Array();
  77044. this._onAfterPhysicsStepCallbacks = new Array();
  77045. this._onPhysicsCollideCallbacks = [];
  77046. this._deltaPosition = BABYLON.Vector3.Zero();
  77047. this._isDisposed = false;
  77048. //temp variables for parent rotation calculations
  77049. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77050. this._tmpQuat = new BABYLON.Quaternion();
  77051. this._tmpQuat2 = new BABYLON.Quaternion();
  77052. /**
  77053. * this function is executed by the physics engine.
  77054. */
  77055. this.beforeStep = function () {
  77056. if (!_this._physicsEngine) {
  77057. return;
  77058. }
  77059. _this.object.translate(_this._deltaPosition, -1);
  77060. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77061. _this.object.computeWorldMatrix(false);
  77062. if (_this.object.parent && _this.object.rotationQuaternion) {
  77063. _this.getParentsRotation();
  77064. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77065. }
  77066. else {
  77067. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77068. }
  77069. if (!_this._options.disableBidirectionalTransformation) {
  77070. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77071. }
  77072. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77073. func(_this);
  77074. });
  77075. };
  77076. /**
  77077. * this function is executed by the physics engine.
  77078. */
  77079. this.afterStep = function () {
  77080. if (!_this._physicsEngine) {
  77081. return;
  77082. }
  77083. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77084. func(_this);
  77085. });
  77086. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77087. // object has now its world rotation. needs to be converted to local.
  77088. if (_this.object.parent && _this.object.rotationQuaternion) {
  77089. _this.getParentsRotation();
  77090. _this._tmpQuat.conjugateInPlace();
  77091. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77092. }
  77093. // take the position set and make it the absolute position of this object.
  77094. _this.object.setAbsolutePosition(_this.object.position);
  77095. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77096. _this.object.translate(_this._deltaPosition, 1);
  77097. };
  77098. /**
  77099. * Legacy collision detection event support
  77100. */
  77101. this.onCollideEvent = null;
  77102. //event and body object due to cannon's event-based architecture.
  77103. this.onCollide = function (e) {
  77104. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77105. return;
  77106. }
  77107. if (!_this._physicsEngine) {
  77108. return;
  77109. }
  77110. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77111. if (otherImpostor) {
  77112. // Legacy collision detection event support
  77113. if (_this.onCollideEvent) {
  77114. _this.onCollideEvent(_this, otherImpostor);
  77115. }
  77116. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77117. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77118. }).forEach(function (obj) {
  77119. obj.callback(_this, otherImpostor);
  77120. });
  77121. }
  77122. };
  77123. //sanity check!
  77124. if (!this.object) {
  77125. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77126. return;
  77127. }
  77128. //legacy support for old syntax.
  77129. if (!this._scene && object.getScene) {
  77130. this._scene = object.getScene();
  77131. }
  77132. if (!this._scene) {
  77133. return;
  77134. }
  77135. this._physicsEngine = this._scene.getPhysicsEngine();
  77136. if (!this._physicsEngine) {
  77137. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77138. }
  77139. else {
  77140. //set the object's quaternion, if not set
  77141. if (!this.object.rotationQuaternion) {
  77142. if (this.object.rotation) {
  77143. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77144. }
  77145. else {
  77146. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77147. }
  77148. }
  77149. //default options params
  77150. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77151. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77152. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77153. this._joints = [];
  77154. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77155. if (!this.object.parent || this._options.ignoreParent) {
  77156. this._init();
  77157. }
  77158. else if (this.object.parent.physicsImpostor) {
  77159. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77160. }
  77161. }
  77162. }
  77163. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77164. get: function () {
  77165. return this._isDisposed;
  77166. },
  77167. enumerable: true,
  77168. configurable: true
  77169. });
  77170. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77171. get: function () {
  77172. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77173. },
  77174. set: function (value) {
  77175. this.setMass(value);
  77176. },
  77177. enumerable: true,
  77178. configurable: true
  77179. });
  77180. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77181. get: function () {
  77182. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77183. },
  77184. set: function (value) {
  77185. if (!this._physicsEngine) {
  77186. return;
  77187. }
  77188. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77189. },
  77190. enumerable: true,
  77191. configurable: true
  77192. });
  77193. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77194. get: function () {
  77195. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77196. },
  77197. set: function (value) {
  77198. if (!this._physicsEngine) {
  77199. return;
  77200. }
  77201. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77202. },
  77203. enumerable: true,
  77204. configurable: true
  77205. });
  77206. /**
  77207. * This function will completly initialize this impostor.
  77208. * It will create a new body - but only if this mesh has no parent.
  77209. * If it has, this impostor will not be used other than to define the impostor
  77210. * of the child mesh.
  77211. */
  77212. PhysicsImpostor.prototype._init = function () {
  77213. if (!this._physicsEngine) {
  77214. return;
  77215. }
  77216. this._physicsEngine.removeImpostor(this);
  77217. this.physicsBody = null;
  77218. this._parent = this._parent || this._getPhysicsParent();
  77219. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77220. this._physicsEngine.addImpostor(this);
  77221. }
  77222. };
  77223. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77224. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77225. var parentMesh = this.object.parent;
  77226. return parentMesh.physicsImpostor;
  77227. }
  77228. return null;
  77229. };
  77230. /**
  77231. * Should a new body be generated.
  77232. */
  77233. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77234. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77235. };
  77236. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77237. this.forceUpdate();
  77238. };
  77239. /**
  77240. * Force a regeneration of this or the parent's impostor's body.
  77241. * Use under cautious - This will remove all joints already implemented.
  77242. */
  77243. PhysicsImpostor.prototype.forceUpdate = function () {
  77244. this._init();
  77245. if (this.parent && !this._options.ignoreParent) {
  77246. this.parent.forceUpdate();
  77247. }
  77248. };
  77249. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77250. /*public get mesh(): AbstractMesh {
  77251. return this._mesh;
  77252. }*/
  77253. /**
  77254. * Gets the body that holds this impostor. Either its own, or its parent.
  77255. */
  77256. get: function () {
  77257. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77258. },
  77259. /**
  77260. * Set the physics body. Used mainly by the physics engine/plugin
  77261. */
  77262. set: function (physicsBody) {
  77263. if (this._physicsBody && this._physicsEngine) {
  77264. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77265. }
  77266. this._physicsBody = physicsBody;
  77267. this.resetUpdateFlags();
  77268. },
  77269. enumerable: true,
  77270. configurable: true
  77271. });
  77272. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77273. get: function () {
  77274. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77275. },
  77276. set: function (value) {
  77277. this._parent = value;
  77278. },
  77279. enumerable: true,
  77280. configurable: true
  77281. });
  77282. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77283. this._bodyUpdateRequired = false;
  77284. };
  77285. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77286. if (this.object.getBoundingInfo) {
  77287. var q = this.object.rotationQuaternion;
  77288. //reset rotation
  77289. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77290. //calculate the world matrix with no rotation
  77291. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77292. var boundingInfo = this.object.getBoundingInfo();
  77293. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77294. //bring back the rotation
  77295. this.object.rotationQuaternion = q;
  77296. //calculate the world matrix with the new rotation
  77297. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77298. return size;
  77299. }
  77300. else {
  77301. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77302. }
  77303. };
  77304. PhysicsImpostor.prototype.getObjectCenter = function () {
  77305. if (this.object.getBoundingInfo) {
  77306. var boundingInfo = this.object.getBoundingInfo();
  77307. return boundingInfo.boundingBox.centerWorld;
  77308. }
  77309. else {
  77310. return this.object.position;
  77311. }
  77312. };
  77313. /**
  77314. * Get a specific parametes from the options parameter.
  77315. */
  77316. PhysicsImpostor.prototype.getParam = function (paramName) {
  77317. return this._options[paramName];
  77318. };
  77319. /**
  77320. * Sets a specific parameter in the options given to the physics plugin
  77321. */
  77322. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77323. this._options[paramName] = value;
  77324. this._bodyUpdateRequired = true;
  77325. };
  77326. /**
  77327. * Specifically change the body's mass option. Won't recreate the physics body object
  77328. */
  77329. PhysicsImpostor.prototype.setMass = function (mass) {
  77330. if (this.getParam("mass") !== mass) {
  77331. this.setParam("mass", mass);
  77332. }
  77333. if (this._physicsEngine) {
  77334. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77335. }
  77336. };
  77337. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77338. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77339. };
  77340. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77341. if (this._physicsEngine) {
  77342. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77343. }
  77344. };
  77345. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77346. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77347. };
  77348. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77349. if (this._physicsEngine) {
  77350. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77351. }
  77352. };
  77353. /**
  77354. * Execute a function with the physics plugin native code.
  77355. * Provide a function the will have two variables - the world object and the physics body object.
  77356. */
  77357. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77358. if (this._physicsEngine) {
  77359. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77360. }
  77361. };
  77362. /**
  77363. * Register a function that will be executed before the physics world is stepping forward.
  77364. */
  77365. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77366. this._onBeforePhysicsStepCallbacks.push(func);
  77367. };
  77368. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77369. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77370. if (index > -1) {
  77371. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77372. }
  77373. else {
  77374. BABYLON.Tools.Warn("Function to remove was not found");
  77375. }
  77376. };
  77377. /**
  77378. * Register a function that will be executed after the physics step
  77379. */
  77380. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77381. this._onAfterPhysicsStepCallbacks.push(func);
  77382. };
  77383. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77384. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77385. if (index > -1) {
  77386. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77387. }
  77388. else {
  77389. BABYLON.Tools.Warn("Function to remove was not found");
  77390. }
  77391. };
  77392. /**
  77393. * register a function that will be executed when this impostor collides against a different body.
  77394. */
  77395. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77396. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77397. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77398. };
  77399. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77400. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77401. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77402. if (index > -1) {
  77403. this._onPhysicsCollideCallbacks.splice(index, 1);
  77404. }
  77405. else {
  77406. BABYLON.Tools.Warn("Function to remove was not found");
  77407. }
  77408. };
  77409. PhysicsImpostor.prototype.getParentsRotation = function () {
  77410. var parent = this.object.parent;
  77411. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77412. while (parent) {
  77413. if (parent.rotationQuaternion) {
  77414. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77415. }
  77416. else {
  77417. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77418. }
  77419. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77420. parent = parent.parent;
  77421. }
  77422. return this._tmpQuat;
  77423. };
  77424. /**
  77425. * Apply a force
  77426. */
  77427. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77428. if (this._physicsEngine) {
  77429. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77430. }
  77431. return this;
  77432. };
  77433. /**
  77434. * Apply an impulse
  77435. */
  77436. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77437. if (this._physicsEngine) {
  77438. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77439. }
  77440. return this;
  77441. };
  77442. /**
  77443. * A help function to create a joint.
  77444. */
  77445. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77446. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77447. this.addJoint(otherImpostor, joint);
  77448. return this;
  77449. };
  77450. /**
  77451. * Add a joint to this impostor with a different impostor.
  77452. */
  77453. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77454. this._joints.push({
  77455. otherImpostor: otherImpostor,
  77456. joint: joint
  77457. });
  77458. if (this._physicsEngine) {
  77459. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77460. }
  77461. return this;
  77462. };
  77463. /**
  77464. * Will keep this body still, in a sleep mode.
  77465. */
  77466. PhysicsImpostor.prototype.sleep = function () {
  77467. if (this._physicsEngine) {
  77468. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77469. }
  77470. return this;
  77471. };
  77472. /**
  77473. * Wake the body up.
  77474. */
  77475. PhysicsImpostor.prototype.wakeUp = function () {
  77476. if (this._physicsEngine) {
  77477. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77478. }
  77479. return this;
  77480. };
  77481. PhysicsImpostor.prototype.clone = function (newObject) {
  77482. if (!newObject)
  77483. return null;
  77484. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77485. };
  77486. PhysicsImpostor.prototype.dispose = function () {
  77487. var _this = this;
  77488. //no dispose if no physics engine is available.
  77489. if (!this._physicsEngine) {
  77490. return;
  77491. }
  77492. this._joints.forEach(function (j) {
  77493. if (_this._physicsEngine) {
  77494. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77495. }
  77496. });
  77497. //dispose the physics body
  77498. this._physicsEngine.removeImpostor(this);
  77499. if (this.parent) {
  77500. this.parent.forceUpdate();
  77501. }
  77502. else {
  77503. /*this._object.getChildMeshes().forEach(function(mesh) {
  77504. if (mesh.physicsImpostor) {
  77505. if (disposeChildren) {
  77506. mesh.physicsImpostor.dispose();
  77507. mesh.physicsImpostor = null;
  77508. }
  77509. }
  77510. })*/
  77511. }
  77512. this._isDisposed = true;
  77513. };
  77514. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77515. this._deltaPosition.copyFrom(position);
  77516. };
  77517. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77518. if (!this._deltaRotation) {
  77519. this._deltaRotation = new BABYLON.Quaternion();
  77520. }
  77521. this._deltaRotation.copyFrom(rotation);
  77522. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77523. };
  77524. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77525. if (this._physicsEngine) {
  77526. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77527. }
  77528. return this;
  77529. };
  77530. PhysicsImpostor.prototype.getRadius = function () {
  77531. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77532. };
  77533. /**
  77534. * Sync a bone with this impostor
  77535. * @param bone The bone to sync to the impostor.
  77536. * @param boneMesh The mesh that the bone is influencing.
  77537. * @param jointPivot The pivot of the joint / bone in local space.
  77538. * @param distToJoint Optional distance from the impostor to the joint.
  77539. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77540. */
  77541. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77542. var tempVec = PhysicsImpostor._tmpVecs[0];
  77543. var mesh = this.object;
  77544. if (mesh.rotationQuaternion) {
  77545. if (adjustRotation) {
  77546. var tempQuat = PhysicsImpostor._tmpQuat;
  77547. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77548. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77549. }
  77550. else {
  77551. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77552. }
  77553. }
  77554. tempVec.x = 0;
  77555. tempVec.y = 0;
  77556. tempVec.z = 0;
  77557. if (jointPivot) {
  77558. tempVec.x = jointPivot.x;
  77559. tempVec.y = jointPivot.y;
  77560. tempVec.z = jointPivot.z;
  77561. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77562. if (distToJoint === undefined || distToJoint === null) {
  77563. distToJoint = jointPivot.length();
  77564. }
  77565. tempVec.x *= distToJoint;
  77566. tempVec.y *= distToJoint;
  77567. tempVec.z *= distToJoint;
  77568. }
  77569. if (bone.getParent()) {
  77570. tempVec.addInPlace(mesh.getAbsolutePosition());
  77571. bone.setAbsolutePosition(tempVec, boneMesh);
  77572. }
  77573. else {
  77574. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77575. boneMesh.position.x -= tempVec.x;
  77576. boneMesh.position.y -= tempVec.y;
  77577. boneMesh.position.z -= tempVec.z;
  77578. }
  77579. };
  77580. /**
  77581. * Sync impostor to a bone
  77582. * @param bone The bone that the impostor will be synced to.
  77583. * @param boneMesh The mesh that the bone is influencing.
  77584. * @param jointPivot The pivot of the joint / bone in local space.
  77585. * @param distToJoint Optional distance from the impostor to the joint.
  77586. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77587. * @param boneAxis Optional vector3 axis the bone is aligned with
  77588. */
  77589. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77590. var mesh = this.object;
  77591. if (mesh.rotationQuaternion) {
  77592. if (adjustRotation) {
  77593. var tempQuat = PhysicsImpostor._tmpQuat;
  77594. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77595. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77596. }
  77597. else {
  77598. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77599. }
  77600. }
  77601. var pos = PhysicsImpostor._tmpVecs[0];
  77602. var boneDir = PhysicsImpostor._tmpVecs[1];
  77603. if (!boneAxis) {
  77604. boneAxis = PhysicsImpostor._tmpVecs[2];
  77605. boneAxis.x = 0;
  77606. boneAxis.y = 1;
  77607. boneAxis.z = 0;
  77608. }
  77609. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77610. bone.getAbsolutePositionToRef(boneMesh, pos);
  77611. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77612. distToJoint = jointPivot.length();
  77613. }
  77614. if (distToJoint !== undefined && distToJoint !== null) {
  77615. pos.x += boneDir.x * distToJoint;
  77616. pos.y += boneDir.y * distToJoint;
  77617. pos.z += boneDir.z * distToJoint;
  77618. }
  77619. mesh.setAbsolutePosition(pos);
  77620. };
  77621. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77622. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77623. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77624. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77625. //Impostor types
  77626. PhysicsImpostor.NoImpostor = 0;
  77627. PhysicsImpostor.SphereImpostor = 1;
  77628. PhysicsImpostor.BoxImpostor = 2;
  77629. PhysicsImpostor.PlaneImpostor = 3;
  77630. PhysicsImpostor.MeshImpostor = 4;
  77631. PhysicsImpostor.CylinderImpostor = 7;
  77632. PhysicsImpostor.ParticleImpostor = 8;
  77633. PhysicsImpostor.HeightmapImpostor = 9;
  77634. return PhysicsImpostor;
  77635. }());
  77636. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77637. })(BABYLON || (BABYLON = {}));
  77638. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77639. "use strict";
  77640. var BABYLON;
  77641. (function (BABYLON) {
  77642. var PhysicsEngine = /** @class */ (function () {
  77643. function PhysicsEngine(gravity, _physicsPlugin) {
  77644. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77645. this._physicsPlugin = _physicsPlugin;
  77646. //new methods and parameters
  77647. this._impostors = [];
  77648. this._joints = [];
  77649. if (!this._physicsPlugin.isSupported()) {
  77650. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77651. + "Please make sure it is included.");
  77652. }
  77653. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77654. this.setGravity(gravity);
  77655. this.setTimeStep();
  77656. }
  77657. PhysicsEngine.prototype.setGravity = function (gravity) {
  77658. this.gravity = gravity;
  77659. this._physicsPlugin.setGravity(this.gravity);
  77660. };
  77661. /**
  77662. * Set the time step of the physics engine.
  77663. * default is 1/60.
  77664. * To slow it down, enter 1/600 for example.
  77665. * To speed it up, 1/30
  77666. * @param {number} newTimeStep the new timestep to apply to this world.
  77667. */
  77668. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77669. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77670. this._physicsPlugin.setTimeStep(newTimeStep);
  77671. };
  77672. /**
  77673. * Get the time step of the physics engine.
  77674. */
  77675. PhysicsEngine.prototype.getTimeStep = function () {
  77676. return this._physicsPlugin.getTimeStep();
  77677. };
  77678. PhysicsEngine.prototype.dispose = function () {
  77679. this._impostors.forEach(function (impostor) {
  77680. impostor.dispose();
  77681. });
  77682. this._physicsPlugin.dispose();
  77683. };
  77684. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77685. return this._physicsPlugin.name;
  77686. };
  77687. /**
  77688. * Adding a new impostor for the impostor tracking.
  77689. * This will be done by the impostor itself.
  77690. * @param {PhysicsImpostor} impostor the impostor to add
  77691. */
  77692. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77693. impostor.uniqueId = this._impostors.push(impostor);
  77694. //if no parent, generate the body
  77695. if (!impostor.parent) {
  77696. this._physicsPlugin.generatePhysicsBody(impostor);
  77697. }
  77698. };
  77699. /**
  77700. * Remove an impostor from the engine.
  77701. * This impostor and its mesh will not longer be updated by the physics engine.
  77702. * @param {PhysicsImpostor} impostor the impostor to remove
  77703. */
  77704. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  77705. var index = this._impostors.indexOf(impostor);
  77706. if (index > -1) {
  77707. var removed = this._impostors.splice(index, 1);
  77708. //Is it needed?
  77709. if (removed.length) {
  77710. //this will also remove it from the world.
  77711. removed[0].physicsBody = null;
  77712. }
  77713. }
  77714. };
  77715. /**
  77716. * Add a joint to the physics engine
  77717. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  77718. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  77719. * @param {PhysicsJoint} the joint that will connect both impostors.
  77720. */
  77721. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  77722. var impostorJoint = {
  77723. mainImpostor: mainImpostor,
  77724. connectedImpostor: connectedImpostor,
  77725. joint: joint
  77726. };
  77727. joint.physicsPlugin = this._physicsPlugin;
  77728. this._joints.push(impostorJoint);
  77729. this._physicsPlugin.generateJoint(impostorJoint);
  77730. };
  77731. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  77732. var matchingJoints = this._joints.filter(function (impostorJoint) {
  77733. return (impostorJoint.connectedImpostor === connectedImpostor
  77734. && impostorJoint.joint === joint
  77735. && impostorJoint.mainImpostor === mainImpostor);
  77736. });
  77737. if (matchingJoints.length) {
  77738. this._physicsPlugin.removeJoint(matchingJoints[0]);
  77739. //TODO remove it from the list as well
  77740. }
  77741. };
  77742. /**
  77743. * Called by the scene. no need to call it.
  77744. */
  77745. PhysicsEngine.prototype._step = function (delta) {
  77746. var _this = this;
  77747. //check if any mesh has no body / requires an update
  77748. this._impostors.forEach(function (impostor) {
  77749. if (impostor.isBodyInitRequired()) {
  77750. _this._physicsPlugin.generatePhysicsBody(impostor);
  77751. }
  77752. });
  77753. if (delta > 0.1) {
  77754. delta = 0.1;
  77755. }
  77756. else if (delta <= 0) {
  77757. delta = 1.0 / 60.0;
  77758. }
  77759. this._physicsPlugin.executeStep(delta, this._impostors);
  77760. };
  77761. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  77762. return this._physicsPlugin;
  77763. };
  77764. PhysicsEngine.prototype.getImpostors = function () {
  77765. return this._impostors;
  77766. };
  77767. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  77768. for (var i = 0; i < this._impostors.length; ++i) {
  77769. if (this._impostors[i].object === object) {
  77770. return this._impostors[i];
  77771. }
  77772. }
  77773. return null;
  77774. };
  77775. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  77776. for (var i = 0; i < this._impostors.length; ++i) {
  77777. if (this._impostors[i].physicsBody === body) {
  77778. return this._impostors[i];
  77779. }
  77780. }
  77781. return null;
  77782. };
  77783. // Statics
  77784. PhysicsEngine.Epsilon = 0.001;
  77785. return PhysicsEngine;
  77786. }());
  77787. BABYLON.PhysicsEngine = PhysicsEngine;
  77788. })(BABYLON || (BABYLON = {}));
  77789. //# sourceMappingURL=babylon.physicsEngine.js.map
  77790. "use strict";
  77791. var BABYLON;
  77792. (function (BABYLON) {
  77793. var PhysicsHelper = /** @class */ (function () {
  77794. function PhysicsHelper(scene) {
  77795. this._scene = scene;
  77796. this._physicsEngine = this._scene.getPhysicsEngine();
  77797. if (!this._physicsEngine) {
  77798. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77799. }
  77800. }
  77801. /**
  77802. * @param {Vector3} origin the origin of the explosion
  77803. * @param {number} radius the explosion radius
  77804. * @param {number} strength the explosion strength
  77805. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77806. */
  77807. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77808. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77809. if (!this._physicsEngine) {
  77810. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77811. return null;
  77812. }
  77813. var impostors = this._physicsEngine.getImpostors();
  77814. if (impostors.length === 0) {
  77815. return null;
  77816. }
  77817. var event = new PhysicsRadialExplosionEvent(this._scene);
  77818. impostors.forEach(function (impostor) {
  77819. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77820. if (!impostorForceAndContactPoint) {
  77821. return;
  77822. }
  77823. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77824. });
  77825. event.dispose(false);
  77826. return event;
  77827. };
  77828. /**
  77829. * @param {Vector3} origin the origin of the explosion
  77830. * @param {number} radius the explosion radius
  77831. * @param {number} strength the explosion strength
  77832. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77833. */
  77834. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77835. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77836. if (!this._physicsEngine) {
  77837. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77838. return null;
  77839. }
  77840. var impostors = this._physicsEngine.getImpostors();
  77841. if (impostors.length === 0) {
  77842. return null;
  77843. }
  77844. var event = new PhysicsRadialExplosionEvent(this._scene);
  77845. impostors.forEach(function (impostor) {
  77846. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77847. if (!impostorForceAndContactPoint) {
  77848. return;
  77849. }
  77850. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77851. });
  77852. event.dispose(false);
  77853. return event;
  77854. };
  77855. /**
  77856. * @param {Vector3} origin the origin of the explosion
  77857. * @param {number} radius the explosion radius
  77858. * @param {number} strength the explosion strength
  77859. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77860. */
  77861. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77862. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77863. if (!this._physicsEngine) {
  77864. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77865. return null;
  77866. }
  77867. var impostors = this._physicsEngine.getImpostors();
  77868. if (impostors.length === 0) {
  77869. return null;
  77870. }
  77871. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77872. event.dispose(false);
  77873. return event;
  77874. };
  77875. /**
  77876. * @param {Vector3} origin the origin of the updraft
  77877. * @param {number} radius the radius of the updraft
  77878. * @param {number} strength the strength of the updraft
  77879. * @param {number} height the height of the updraft
  77880. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77881. */
  77882. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77883. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77884. if (!this._physicsEngine) {
  77885. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77886. return null;
  77887. }
  77888. if (this._physicsEngine.getImpostors().length === 0) {
  77889. return null;
  77890. }
  77891. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77892. event.dispose(false);
  77893. return event;
  77894. };
  77895. /**
  77896. * @param {Vector3} origin the of the vortex
  77897. * @param {number} radius the radius of the vortex
  77898. * @param {number} strength the strength of the vortex
  77899. * @param {number} height the height of the vortex
  77900. */
  77901. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77902. if (!this._physicsEngine) {
  77903. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77904. return null;
  77905. }
  77906. if (this._physicsEngine.getImpostors().length === 0) {
  77907. return null;
  77908. }
  77909. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77910. event.dispose(false);
  77911. return event;
  77912. };
  77913. return PhysicsHelper;
  77914. }());
  77915. BABYLON.PhysicsHelper = PhysicsHelper;
  77916. /***** Radial explosion *****/
  77917. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77918. function PhysicsRadialExplosionEvent(scene) {
  77919. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77920. this._rays = [];
  77921. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77922. this._scene = scene;
  77923. }
  77924. /**
  77925. * Returns the data related to the radial explosion event (sphere & rays).
  77926. * @returns {PhysicsRadialExplosionEventData}
  77927. */
  77928. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77929. this._dataFetched = true;
  77930. return {
  77931. sphere: this._sphere,
  77932. rays: this._rays,
  77933. };
  77934. };
  77935. /**
  77936. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77937. * @param impostor
  77938. * @param {Vector3} origin the origin of the explosion
  77939. * @param {number} radius the explosion radius
  77940. * @param {number} strength the explosion strength
  77941. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77942. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77943. */
  77944. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77945. if (impostor.mass === 0) {
  77946. return null;
  77947. }
  77948. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77949. return null;
  77950. }
  77951. if (impostor.object.getClassName() !== 'Mesh') {
  77952. return null;
  77953. }
  77954. var impostorObject = impostor.object;
  77955. var impostorObjectCenter = impostor.getObjectCenter();
  77956. var direction = impostorObjectCenter.subtract(origin);
  77957. var ray = new BABYLON.Ray(origin, direction, radius);
  77958. this._rays.push(ray);
  77959. var hit = ray.intersectsMesh(impostorObject);
  77960. var contactPoint = hit.pickedPoint;
  77961. if (!contactPoint) {
  77962. return null;
  77963. }
  77964. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77965. if (distanceFromOrigin > radius) {
  77966. return null;
  77967. }
  77968. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77969. ? strength
  77970. : strength * (1 - (distanceFromOrigin / radius));
  77971. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77972. return { force: force, contactPoint: contactPoint };
  77973. };
  77974. /**
  77975. * Disposes the sphere.
  77976. * @param {bolean} force
  77977. */
  77978. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77979. var _this = this;
  77980. if (force === void 0) { force = true; }
  77981. if (force) {
  77982. this._sphere.dispose();
  77983. }
  77984. else {
  77985. setTimeout(function () {
  77986. if (!_this._dataFetched) {
  77987. _this._sphere.dispose();
  77988. }
  77989. }, 0);
  77990. }
  77991. };
  77992. /*** Helpers ***/
  77993. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77994. if (!this._sphere) {
  77995. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77996. this._sphere.isVisible = false;
  77997. }
  77998. };
  77999. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  78000. var impostorObject = impostor.object;
  78001. this._prepareSphere();
  78002. this._sphere.position = origin;
  78003. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  78004. this._sphere._updateBoundingInfo();
  78005. this._sphere.computeWorldMatrix(true);
  78006. return this._sphere.intersectsMesh(impostorObject, true);
  78007. };
  78008. return PhysicsRadialExplosionEvent;
  78009. }());
  78010. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  78011. /***** Gravitational Field *****/
  78012. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  78013. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  78014. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78015. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78016. this._physicsHelper = physicsHelper;
  78017. this._scene = scene;
  78018. this._origin = origin;
  78019. this._radius = radius;
  78020. this._strength = strength;
  78021. this._falloff = falloff;
  78022. this._tickCallback = this._tick.bind(this);
  78023. }
  78024. /**
  78025. * Returns the data related to the gravitational field event (sphere).
  78026. * @returns {PhysicsGravitationalFieldEventData}
  78027. */
  78028. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  78029. this._dataFetched = true;
  78030. return {
  78031. sphere: this._sphere,
  78032. };
  78033. };
  78034. /**
  78035. * Enables the gravitational field.
  78036. */
  78037. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78038. this._tickCallback.call(this);
  78039. this._scene.registerBeforeRender(this._tickCallback);
  78040. };
  78041. /**
  78042. * Disables the gravitational field.
  78043. */
  78044. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78045. this._scene.unregisterBeforeRender(this._tickCallback);
  78046. };
  78047. /**
  78048. * Disposes the sphere.
  78049. * @param {bolean} force
  78050. */
  78051. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78052. var _this = this;
  78053. if (force === void 0) { force = true; }
  78054. if (force) {
  78055. this._sphere.dispose();
  78056. }
  78057. else {
  78058. setTimeout(function () {
  78059. if (!_this._dataFetched) {
  78060. _this._sphere.dispose();
  78061. }
  78062. }, 0);
  78063. }
  78064. };
  78065. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78066. // Since the params won't change, we fetch the event only once
  78067. if (this._sphere) {
  78068. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78069. }
  78070. else {
  78071. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78072. if (radialExplosionEvent) {
  78073. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78074. }
  78075. }
  78076. };
  78077. return PhysicsGravitationalFieldEvent;
  78078. }());
  78079. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78080. /***** Updraft *****/
  78081. var PhysicsUpdraftEvent = /** @class */ (function () {
  78082. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78083. this._scene = _scene;
  78084. this._origin = _origin;
  78085. this._radius = _radius;
  78086. this._strength = _strength;
  78087. this._height = _height;
  78088. this._updraftMode = _updraftMode;
  78089. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78090. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78091. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78092. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78093. this._physicsEngine = this._scene.getPhysicsEngine();
  78094. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78095. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78096. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78097. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78098. }
  78099. this._tickCallback = this._tick.bind(this);
  78100. }
  78101. /**
  78102. * Returns the data related to the updraft event (cylinder).
  78103. * @returns {PhysicsUpdraftEventData}
  78104. */
  78105. PhysicsUpdraftEvent.prototype.getData = function () {
  78106. this._dataFetched = true;
  78107. return {
  78108. cylinder: this._cylinder,
  78109. };
  78110. };
  78111. /**
  78112. * Enables the updraft.
  78113. */
  78114. PhysicsUpdraftEvent.prototype.enable = function () {
  78115. this._tickCallback.call(this);
  78116. this._scene.registerBeforeRender(this._tickCallback);
  78117. };
  78118. /**
  78119. * Disables the cortex.
  78120. */
  78121. PhysicsUpdraftEvent.prototype.disable = function () {
  78122. this._scene.unregisterBeforeRender(this._tickCallback);
  78123. };
  78124. /**
  78125. * Disposes the sphere.
  78126. * @param {bolean} force
  78127. */
  78128. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78129. var _this = this;
  78130. if (force === void 0) { force = true; }
  78131. if (force) {
  78132. this._cylinder.dispose();
  78133. }
  78134. else {
  78135. setTimeout(function () {
  78136. if (!_this._dataFetched) {
  78137. _this._cylinder.dispose();
  78138. }
  78139. }, 0);
  78140. }
  78141. };
  78142. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78143. if (impostor.mass === 0) {
  78144. return null;
  78145. }
  78146. if (!this._intersectsWithCylinder(impostor)) {
  78147. return null;
  78148. }
  78149. var impostorObjectCenter = impostor.getObjectCenter();
  78150. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78151. var direction = this._originDirection;
  78152. }
  78153. else {
  78154. var direction = impostorObjectCenter.subtract(this._originTop);
  78155. }
  78156. var multiplier = this._strength * -1;
  78157. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78158. return { force: force, contactPoint: impostorObjectCenter };
  78159. };
  78160. PhysicsUpdraftEvent.prototype._tick = function () {
  78161. var _this = this;
  78162. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78163. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78164. if (!impostorForceAndContactPoint) {
  78165. return;
  78166. }
  78167. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78168. });
  78169. };
  78170. /*** Helpers ***/
  78171. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78172. if (!this._cylinder) {
  78173. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78174. height: this._height,
  78175. diameter: this._radius * 2,
  78176. }, this._scene);
  78177. this._cylinder.isVisible = false;
  78178. }
  78179. };
  78180. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78181. var impostorObject = impostor.object;
  78182. this._prepareCylinder();
  78183. this._cylinder.position = this._cylinderPosition;
  78184. return this._cylinder.intersectsMesh(impostorObject, true);
  78185. };
  78186. return PhysicsUpdraftEvent;
  78187. }());
  78188. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78189. /***** Vortex *****/
  78190. var PhysicsVortexEvent = /** @class */ (function () {
  78191. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78192. this._scene = _scene;
  78193. this._origin = _origin;
  78194. this._radius = _radius;
  78195. this._strength = _strength;
  78196. this._height = _height;
  78197. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78198. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78199. this._updraftMultiplier = 0.02;
  78200. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78201. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78202. this._physicsEngine = this._scene.getPhysicsEngine();
  78203. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78204. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78205. this._tickCallback = this._tick.bind(this);
  78206. }
  78207. /**
  78208. * Returns the data related to the vortex event (cylinder).
  78209. * @returns {PhysicsVortexEventData}
  78210. */
  78211. PhysicsVortexEvent.prototype.getData = function () {
  78212. this._dataFetched = true;
  78213. return {
  78214. cylinder: this._cylinder,
  78215. };
  78216. };
  78217. /**
  78218. * Enables the vortex.
  78219. */
  78220. PhysicsVortexEvent.prototype.enable = function () {
  78221. this._tickCallback.call(this);
  78222. this._scene.registerBeforeRender(this._tickCallback);
  78223. };
  78224. /**
  78225. * Disables the cortex.
  78226. */
  78227. PhysicsVortexEvent.prototype.disable = function () {
  78228. this._scene.unregisterBeforeRender(this._tickCallback);
  78229. };
  78230. /**
  78231. * Disposes the sphere.
  78232. * @param {bolean} force
  78233. */
  78234. PhysicsVortexEvent.prototype.dispose = function (force) {
  78235. var _this = this;
  78236. if (force === void 0) { force = true; }
  78237. if (force) {
  78238. this._cylinder.dispose();
  78239. }
  78240. else {
  78241. setTimeout(function () {
  78242. if (!_this._dataFetched) {
  78243. _this._cylinder.dispose();
  78244. }
  78245. }, 0);
  78246. }
  78247. };
  78248. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78249. if (impostor.mass === 0) {
  78250. return null;
  78251. }
  78252. if (!this._intersectsWithCylinder(impostor)) {
  78253. return null;
  78254. }
  78255. if (impostor.object.getClassName() !== 'Mesh') {
  78256. return null;
  78257. }
  78258. var impostorObject = impostor.object;
  78259. var impostorObjectCenter = impostor.getObjectCenter();
  78260. 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)
  78261. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78262. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78263. var hit = ray.intersectsMesh(impostorObject);
  78264. var contactPoint = hit.pickedPoint;
  78265. if (!contactPoint) {
  78266. return null;
  78267. }
  78268. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78269. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78270. var directionToOrigin = contactPoint.normalize();
  78271. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78272. directionToOrigin = directionToOrigin.negate();
  78273. }
  78274. // TODO: find a more physically based solution
  78275. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78276. var forceX = directionToOrigin.x * this._strength / 8;
  78277. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78278. var forceZ = directionToOrigin.z * this._strength / 8;
  78279. }
  78280. else {
  78281. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78282. var forceY = this._originTop.y * this._updraftMultiplier;
  78283. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78284. }
  78285. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78286. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78287. return { force: force, contactPoint: impostorObjectCenter };
  78288. };
  78289. PhysicsVortexEvent.prototype._tick = function () {
  78290. var _this = this;
  78291. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78292. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78293. if (!impostorForceAndContactPoint) {
  78294. return;
  78295. }
  78296. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78297. });
  78298. };
  78299. /*** Helpers ***/
  78300. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78301. if (!this._cylinder) {
  78302. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78303. height: this._height,
  78304. diameter: this._radius * 2,
  78305. }, this._scene);
  78306. this._cylinder.isVisible = false;
  78307. }
  78308. };
  78309. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78310. var impostorObject = impostor.object;
  78311. this._prepareCylinder();
  78312. this._cylinder.position = this._cylinderPosition;
  78313. return this._cylinder.intersectsMesh(impostorObject, true);
  78314. };
  78315. return PhysicsVortexEvent;
  78316. }());
  78317. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78318. /***** Enums *****/
  78319. /**
  78320. * The strenght of the force in correspondence to the distance of the affected object
  78321. */
  78322. var PhysicsRadialImpulseFalloff;
  78323. (function (PhysicsRadialImpulseFalloff) {
  78324. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78325. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78326. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78327. /**
  78328. * The strenght of the force in correspondence to the distance of the affected object
  78329. */
  78330. var PhysicsUpdraftMode;
  78331. (function (PhysicsUpdraftMode) {
  78332. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78333. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78334. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78335. })(BABYLON || (BABYLON = {}));
  78336. //# sourceMappingURL=babylon.physicsHelper.js.map
  78337. "use strict";
  78338. var BABYLON;
  78339. (function (BABYLON) {
  78340. var CannonJSPlugin = /** @class */ (function () {
  78341. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78342. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78343. if (iterations === void 0) { iterations = 10; }
  78344. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78345. this.name = "CannonJSPlugin";
  78346. this._physicsMaterials = new Array();
  78347. this._fixedTimeStep = 1 / 60;
  78348. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78349. this.BJSCANNON = CANNON;
  78350. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78351. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78352. this._tmpPosition = BABYLON.Vector3.Zero();
  78353. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78354. this._tmpUnityRotation = new BABYLON.Quaternion();
  78355. if (!this.isSupported()) {
  78356. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78357. return;
  78358. }
  78359. this._extendNamespace();
  78360. this.world = new this.BJSCANNON.World();
  78361. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78362. this.world.solver.iterations = iterations;
  78363. }
  78364. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78365. this.world.gravity.copy(gravity);
  78366. };
  78367. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78368. this._fixedTimeStep = timeStep;
  78369. };
  78370. CannonJSPlugin.prototype.getTimeStep = function () {
  78371. return this._fixedTimeStep;
  78372. };
  78373. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78374. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78375. };
  78376. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78377. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78378. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78379. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78380. };
  78381. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78382. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78383. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78384. impostor.physicsBody.applyForce(impulse, worldPoint);
  78385. };
  78386. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78387. //parent-child relationship. Does this impostor has a parent impostor?
  78388. if (impostor.parent) {
  78389. if (impostor.physicsBody) {
  78390. this.removePhysicsBody(impostor);
  78391. //TODO is that needed?
  78392. impostor.forceUpdate();
  78393. }
  78394. return;
  78395. }
  78396. //should a new body be created for this impostor?
  78397. if (impostor.isBodyInitRequired()) {
  78398. var shape = this._createShape(impostor);
  78399. //unregister events, if body is being changed
  78400. var oldBody = impostor.physicsBody;
  78401. if (oldBody) {
  78402. this.removePhysicsBody(impostor);
  78403. }
  78404. //create the body and material
  78405. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78406. var bodyCreationObject = {
  78407. mass: impostor.getParam("mass"),
  78408. material: material
  78409. };
  78410. // A simple extend, in case native options were used.
  78411. var nativeOptions = impostor.getParam("nativeOptions");
  78412. for (var key in nativeOptions) {
  78413. if (nativeOptions.hasOwnProperty(key)) {
  78414. bodyCreationObject[key] = nativeOptions[key];
  78415. }
  78416. }
  78417. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78418. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78419. this.world.addEventListener("preStep", impostor.beforeStep);
  78420. this.world.addEventListener("postStep", impostor.afterStep);
  78421. impostor.physicsBody.addShape(shape);
  78422. this.world.add(impostor.physicsBody);
  78423. //try to keep the body moving in the right direction by taking old properties.
  78424. //Should be tested!
  78425. if (oldBody) {
  78426. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78427. impostor.physicsBody[param].copy(oldBody[param]);
  78428. });
  78429. }
  78430. this._processChildMeshes(impostor);
  78431. }
  78432. //now update the body's transformation
  78433. this._updatePhysicsBodyTransformation(impostor);
  78434. };
  78435. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78436. var _this = this;
  78437. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78438. var currentRotation = mainImpostor.object.rotationQuaternion;
  78439. if (meshChildren.length) {
  78440. var processMesh = function (localPosition, mesh) {
  78441. if (!currentRotation || !mesh.rotationQuaternion) {
  78442. return;
  78443. }
  78444. var childImpostor = mesh.getPhysicsImpostor();
  78445. if (childImpostor) {
  78446. var parent = childImpostor.parent;
  78447. if (parent !== mainImpostor) {
  78448. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78449. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78450. if (childImpostor.physicsBody) {
  78451. _this.removePhysicsBody(childImpostor);
  78452. childImpostor.physicsBody = null;
  78453. }
  78454. childImpostor.parent = mainImpostor;
  78455. childImpostor.resetUpdateFlags();
  78456. 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));
  78457. //Add the mass of the children.
  78458. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78459. }
  78460. }
  78461. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78462. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78463. };
  78464. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78465. }
  78466. };
  78467. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78468. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78469. this.world.removeEventListener("preStep", impostor.beforeStep);
  78470. this.world.removeEventListener("postStep", impostor.afterStep);
  78471. this.world.remove(impostor.physicsBody);
  78472. };
  78473. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78474. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78475. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78476. if (!mainBody || !connectedBody) {
  78477. return;
  78478. }
  78479. var constraint;
  78480. var jointData = impostorJoint.joint.jointData;
  78481. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78482. var constraintData = {
  78483. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78484. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78485. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78486. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78487. maxForce: jointData.nativeParams.maxForce,
  78488. collideConnected: !!jointData.collision
  78489. };
  78490. switch (impostorJoint.joint.type) {
  78491. case BABYLON.PhysicsJoint.HingeJoint:
  78492. case BABYLON.PhysicsJoint.Hinge2Joint:
  78493. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78494. break;
  78495. case BABYLON.PhysicsJoint.DistanceJoint:
  78496. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78497. break;
  78498. case BABYLON.PhysicsJoint.SpringJoint:
  78499. var springData = jointData;
  78500. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78501. restLength: springData.length,
  78502. stiffness: springData.stiffness,
  78503. damping: springData.damping,
  78504. localAnchorA: constraintData.pivotA,
  78505. localAnchorB: constraintData.pivotB
  78506. });
  78507. break;
  78508. case BABYLON.PhysicsJoint.LockJoint:
  78509. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78510. break;
  78511. case BABYLON.PhysicsJoint.PointToPointJoint:
  78512. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78513. default:
  78514. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78515. break;
  78516. }
  78517. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78518. constraint.collideConnected = !!jointData.collision;
  78519. impostorJoint.joint.physicsJoint = constraint;
  78520. //don't add spring as constraint, as it is not one.
  78521. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78522. this.world.addConstraint(constraint);
  78523. }
  78524. else {
  78525. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78526. constraint.applyForce();
  78527. });
  78528. }
  78529. };
  78530. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78531. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78532. };
  78533. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78534. var index;
  78535. var mat;
  78536. for (index = 0; index < this._physicsMaterials.length; index++) {
  78537. mat = this._physicsMaterials[index];
  78538. if (mat.friction === friction && mat.restitution === restitution) {
  78539. return mat;
  78540. }
  78541. }
  78542. var currentMat = new this.BJSCANNON.Material(name);
  78543. currentMat.friction = friction;
  78544. currentMat.restitution = restitution;
  78545. this._physicsMaterials.push(currentMat);
  78546. return currentMat;
  78547. };
  78548. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78549. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78550. };
  78551. CannonJSPlugin.prototype._createShape = function (impostor) {
  78552. var object = impostor.object;
  78553. var returnValue;
  78554. var extendSize = impostor.getObjectExtendSize();
  78555. switch (impostor.type) {
  78556. case BABYLON.PhysicsImpostor.SphereImpostor:
  78557. var radiusX = extendSize.x;
  78558. var radiusY = extendSize.y;
  78559. var radiusZ = extendSize.z;
  78560. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78561. break;
  78562. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78563. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78564. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78565. break;
  78566. case BABYLON.PhysicsImpostor.BoxImpostor:
  78567. var box = extendSize.scale(0.5);
  78568. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78569. break;
  78570. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78571. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78572. returnValue = new this.BJSCANNON.Plane();
  78573. break;
  78574. case BABYLON.PhysicsImpostor.MeshImpostor:
  78575. // should transform the vertex data to world coordinates!!
  78576. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78577. var rawFaces = object.getIndices ? object.getIndices() : [];
  78578. if (!rawVerts)
  78579. return;
  78580. // get only scale! so the object could transform correctly.
  78581. var oldPosition = object.position.clone();
  78582. var oldRotation = object.rotation && object.rotation.clone();
  78583. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78584. object.position.copyFromFloats(0, 0, 0);
  78585. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78586. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78587. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78588. var transform = object.computeWorldMatrix(true);
  78589. // convert rawVerts to object space
  78590. var temp = new Array();
  78591. var index;
  78592. for (index = 0; index < rawVerts.length; index += 3) {
  78593. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78594. }
  78595. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78596. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78597. //now set back the transformation!
  78598. object.position.copyFrom(oldPosition);
  78599. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78600. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78601. break;
  78602. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78603. var oldPosition2 = object.position.clone();
  78604. var oldRotation2 = object.rotation && object.rotation.clone();
  78605. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78606. object.position.copyFromFloats(0, 0, 0);
  78607. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78608. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78609. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78610. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78611. returnValue = this._createHeightmap(object);
  78612. object.position.copyFrom(oldPosition2);
  78613. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78614. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78615. object.computeWorldMatrix(true);
  78616. break;
  78617. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78618. returnValue = new this.BJSCANNON.Particle();
  78619. break;
  78620. }
  78621. return returnValue;
  78622. };
  78623. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78624. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78625. var transform = object.computeWorldMatrix(true);
  78626. // convert rawVerts to object space
  78627. var temp = new Array();
  78628. var index;
  78629. for (index = 0; index < pos.length; index += 3) {
  78630. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78631. }
  78632. pos = temp;
  78633. var matrix = new Array();
  78634. //For now pointDepth will not be used and will be automatically calculated.
  78635. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78636. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78637. var boundingInfo = object.getBoundingInfo();
  78638. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78639. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78640. var elementSize = dim * 2 / arraySize;
  78641. for (var i = 0; i < pos.length; i = i + 3) {
  78642. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78643. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78644. var y = -pos[i + 2] + minY;
  78645. if (!matrix[x]) {
  78646. matrix[x] = [];
  78647. }
  78648. if (!matrix[x][z]) {
  78649. matrix[x][z] = y;
  78650. }
  78651. matrix[x][z] = Math.max(y, matrix[x][z]);
  78652. }
  78653. for (var x = 0; x <= arraySize; ++x) {
  78654. if (!matrix[x]) {
  78655. var loc = 1;
  78656. while (!matrix[(x + loc) % arraySize]) {
  78657. loc++;
  78658. }
  78659. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78660. //console.log("missing x", x);
  78661. }
  78662. for (var z = 0; z <= arraySize; ++z) {
  78663. if (!matrix[x][z]) {
  78664. var loc = 1;
  78665. var newValue;
  78666. while (newValue === undefined) {
  78667. newValue = matrix[x][(z + loc++) % arraySize];
  78668. }
  78669. matrix[x][z] = newValue;
  78670. }
  78671. }
  78672. }
  78673. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78674. elementSize: elementSize
  78675. });
  78676. //For future reference, needed for body transformation
  78677. shape.minY = minY;
  78678. return shape;
  78679. };
  78680. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78681. var object = impostor.object;
  78682. //make sure it is updated...
  78683. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78684. // The delta between the mesh position and the mesh bounding box center
  78685. var bInfo = object.getBoundingInfo();
  78686. if (!bInfo)
  78687. return;
  78688. var center = impostor.getObjectCenter();
  78689. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78690. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78691. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78692. this._tmpPosition.copyFrom(center);
  78693. var quaternion = object.rotationQuaternion;
  78694. if (!quaternion) {
  78695. return;
  78696. }
  78697. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  78698. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  78699. //-90 DEG in X, precalculated
  78700. quaternion = quaternion.multiply(this._minus90X);
  78701. //Invert! (Precalculated, 90 deg in X)
  78702. //No need to clone. this will never change.
  78703. impostor.setDeltaRotation(this._plus90X);
  78704. }
  78705. //If it is a heightfield, if should be centered.
  78706. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78707. var mesh = object;
  78708. var boundingInfo = mesh.getBoundingInfo();
  78709. //calculate the correct body position:
  78710. var rotationQuaternion = mesh.rotationQuaternion;
  78711. mesh.rotationQuaternion = this._tmpUnityRotation;
  78712. mesh.computeWorldMatrix(true);
  78713. //get original center with no rotation
  78714. var c = center.clone();
  78715. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78716. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78717. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78718. mesh.setPreTransformMatrix(p);
  78719. mesh.computeWorldMatrix(true);
  78720. //calculate the translation
  78721. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  78722. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  78723. //add it inverted to the delta
  78724. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  78725. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  78726. //rotation is back
  78727. mesh.rotationQuaternion = rotationQuaternion;
  78728. mesh.setPreTransformMatrix(oldPivot);
  78729. mesh.computeWorldMatrix(true);
  78730. }
  78731. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  78732. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  78733. //this._tmpPosition.copyFrom(object.position);
  78734. }
  78735. impostor.setDeltaPosition(this._tmpDeltaPosition);
  78736. //Now update the impostor object
  78737. impostor.physicsBody.position.copy(this._tmpPosition);
  78738. impostor.physicsBody.quaternion.copy(quaternion);
  78739. };
  78740. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78741. impostor.object.position.copyFrom(impostor.physicsBody.position);
  78742. if (impostor.object.rotationQuaternion) {
  78743. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  78744. }
  78745. };
  78746. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78747. impostor.physicsBody.position.copy(newPosition);
  78748. impostor.physicsBody.quaternion.copy(newRotation);
  78749. };
  78750. CannonJSPlugin.prototype.isSupported = function () {
  78751. return this.BJSCANNON !== undefined;
  78752. };
  78753. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78754. impostor.physicsBody.velocity.copy(velocity);
  78755. };
  78756. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78757. impostor.physicsBody.angularVelocity.copy(velocity);
  78758. };
  78759. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78760. var v = impostor.physicsBody.velocity;
  78761. if (!v) {
  78762. return null;
  78763. }
  78764. return new BABYLON.Vector3(v.x, v.y, v.z);
  78765. };
  78766. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78767. var v = impostor.physicsBody.angularVelocity;
  78768. if (!v) {
  78769. return null;
  78770. }
  78771. return new BABYLON.Vector3(v.x, v.y, v.z);
  78772. };
  78773. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78774. impostor.physicsBody.mass = mass;
  78775. impostor.physicsBody.updateMassProperties();
  78776. };
  78777. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  78778. return impostor.physicsBody.mass;
  78779. };
  78780. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78781. return impostor.physicsBody.material.friction;
  78782. };
  78783. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78784. impostor.physicsBody.material.friction = friction;
  78785. };
  78786. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78787. return impostor.physicsBody.material.restitution;
  78788. };
  78789. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78790. impostor.physicsBody.material.restitution = restitution;
  78791. };
  78792. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78793. impostor.physicsBody.sleep();
  78794. };
  78795. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78796. impostor.physicsBody.wakeUp();
  78797. };
  78798. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78799. joint.physicsJoint.distance = maxDistance;
  78800. };
  78801. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78802. // if (!motorIndex) {
  78803. // joint.physicsJoint.enableMotor();
  78804. // }
  78805. // }
  78806. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78807. // if (!motorIndex) {
  78808. // joint.physicsJoint.disableMotor();
  78809. // }
  78810. // }
  78811. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78812. if (!motorIndex) {
  78813. joint.physicsJoint.enableMotor();
  78814. joint.physicsJoint.setMotorSpeed(speed);
  78815. if (maxForce) {
  78816. this.setLimit(joint, maxForce);
  78817. }
  78818. }
  78819. };
  78820. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78821. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78822. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78823. };
  78824. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78825. var body = impostor.physicsBody;
  78826. mesh.position.x = body.position.x;
  78827. mesh.position.y = body.position.y;
  78828. mesh.position.z = body.position.z;
  78829. if (mesh.rotationQuaternion) {
  78830. mesh.rotationQuaternion.x = body.quaternion.x;
  78831. mesh.rotationQuaternion.y = body.quaternion.y;
  78832. mesh.rotationQuaternion.z = body.quaternion.z;
  78833. mesh.rotationQuaternion.w = body.quaternion.w;
  78834. }
  78835. };
  78836. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78837. var shape = impostor.physicsBody.shapes[0];
  78838. return shape.boundingSphereRadius;
  78839. };
  78840. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78841. var shape = impostor.physicsBody.shapes[0];
  78842. result.x = shape.halfExtents.x * 2;
  78843. result.y = shape.halfExtents.y * 2;
  78844. result.z = shape.halfExtents.z * 2;
  78845. };
  78846. CannonJSPlugin.prototype.dispose = function () {
  78847. };
  78848. CannonJSPlugin.prototype._extendNamespace = function () {
  78849. //this will force cannon to execute at least one step when using interpolation
  78850. var step_tmp1 = new this.BJSCANNON.Vec3();
  78851. var Engine = this.BJSCANNON;
  78852. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78853. maxSubSteps = maxSubSteps || 10;
  78854. timeSinceLastCalled = timeSinceLastCalled || 0;
  78855. if (timeSinceLastCalled === 0) {
  78856. this.internalStep(dt);
  78857. this.time += dt;
  78858. }
  78859. else {
  78860. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78861. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78862. var t0 = performance.now();
  78863. for (var i = 0; i !== internalSteps; i++) {
  78864. this.internalStep(dt);
  78865. if (performance.now() - t0 > dt * 1000) {
  78866. break;
  78867. }
  78868. }
  78869. this.time += timeSinceLastCalled;
  78870. var h = this.time % dt;
  78871. var h_div_dt = h / dt;
  78872. var interpvelo = step_tmp1;
  78873. var bodies = this.bodies;
  78874. for (var j = 0; j !== bodies.length; j++) {
  78875. var b = bodies[j];
  78876. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78877. b.position.vsub(b.previousPosition, interpvelo);
  78878. interpvelo.scale(h_div_dt, interpvelo);
  78879. b.position.vadd(interpvelo, b.interpolatedPosition);
  78880. }
  78881. else {
  78882. b.interpolatedPosition.copy(b.position);
  78883. b.interpolatedQuaternion.copy(b.quaternion);
  78884. }
  78885. }
  78886. }
  78887. };
  78888. };
  78889. return CannonJSPlugin;
  78890. }());
  78891. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78892. })(BABYLON || (BABYLON = {}));
  78893. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78894. "use strict";
  78895. var BABYLON;
  78896. (function (BABYLON) {
  78897. var OimoJSPlugin = /** @class */ (function () {
  78898. function OimoJSPlugin(iterations) {
  78899. this.name = "OimoJSPlugin";
  78900. this._tmpImpostorsArray = [];
  78901. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78902. this.BJSOIMO = OIMO;
  78903. this.world = new this.BJSOIMO.World({
  78904. iterations: iterations
  78905. });
  78906. this.world.clear();
  78907. }
  78908. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78909. this.world.gravity.copy(gravity);
  78910. };
  78911. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78912. this.world.timeStep = timeStep;
  78913. };
  78914. OimoJSPlugin.prototype.getTimeStep = function () {
  78915. return this.world.timeStep;
  78916. };
  78917. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78918. var _this = this;
  78919. impostors.forEach(function (impostor) {
  78920. impostor.beforeStep();
  78921. });
  78922. this.world.step();
  78923. impostors.forEach(function (impostor) {
  78924. impostor.afterStep();
  78925. //update the ordered impostors array
  78926. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78927. });
  78928. //check for collisions
  78929. var contact = this.world.contacts;
  78930. while (contact !== null) {
  78931. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78932. contact = contact.next;
  78933. continue;
  78934. }
  78935. //is this body colliding with any other? get the impostor
  78936. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78937. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78938. if (!mainImpostor || !collidingImpostor) {
  78939. contact = contact.next;
  78940. continue;
  78941. }
  78942. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78943. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78944. contact = contact.next;
  78945. }
  78946. };
  78947. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78948. var mass = impostor.physicsBody.mass;
  78949. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  78950. };
  78951. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78952. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78953. this.applyImpulse(impostor, force, contactPoint);
  78954. };
  78955. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78956. var _this = this;
  78957. //parent-child relationship. Does this impostor has a parent impostor?
  78958. if (impostor.parent) {
  78959. if (impostor.physicsBody) {
  78960. this.removePhysicsBody(impostor);
  78961. //TODO is that needed?
  78962. impostor.forceUpdate();
  78963. }
  78964. return;
  78965. }
  78966. if (impostor.isBodyInitRequired()) {
  78967. var bodyConfig = {
  78968. name: impostor.uniqueId,
  78969. //Oimo must have mass, also for static objects.
  78970. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78971. size: [],
  78972. type: [],
  78973. pos: [],
  78974. posShape: [],
  78975. rot: [],
  78976. rotShape: [],
  78977. move: impostor.getParam("mass") !== 0,
  78978. density: impostor.getParam("mass"),
  78979. friction: impostor.getParam("friction"),
  78980. restitution: impostor.getParam("restitution"),
  78981. //Supporting older versions of Oimo
  78982. world: this.world
  78983. };
  78984. var impostors = [impostor];
  78985. var addToArray = function (parent) {
  78986. if (!parent.getChildMeshes)
  78987. return;
  78988. parent.getChildMeshes().forEach(function (m) {
  78989. if (m.physicsImpostor) {
  78990. impostors.push(m.physicsImpostor);
  78991. //m.physicsImpostor._init();
  78992. }
  78993. });
  78994. };
  78995. addToArray(impostor.object);
  78996. var checkWithEpsilon_1 = function (value) {
  78997. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78998. };
  78999. impostors.forEach(function (i) {
  79000. if (!i.object.rotationQuaternion) {
  79001. return;
  79002. }
  79003. //get the correct bounding box
  79004. var oldQuaternion = i.object.rotationQuaternion;
  79005. var rot = oldQuaternion.toEulerAngles();
  79006. var extendSize = i.getObjectExtendSize();
  79007. var radToDeg = 57.295779513082320876;
  79008. if (i === impostor) {
  79009. var center = impostor.getObjectCenter();
  79010. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  79011. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  79012. //Can also use Array.prototype.push.apply
  79013. bodyConfig.pos.push(center.x);
  79014. bodyConfig.pos.push(center.y);
  79015. bodyConfig.pos.push(center.z);
  79016. bodyConfig.posShape.push(0, 0, 0);
  79017. //tmp solution
  79018. bodyConfig.rot.push(rot.x * radToDeg);
  79019. bodyConfig.rot.push(rot.y * radToDeg);
  79020. bodyConfig.rot.push(rot.z * radToDeg);
  79021. bodyConfig.rotShape.push(0, 0, 0);
  79022. }
  79023. else {
  79024. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  79025. bodyConfig.posShape.push(localPosition.x);
  79026. bodyConfig.posShape.push(localPosition.y);
  79027. bodyConfig.posShape.push(localPosition.z);
  79028. bodyConfig.pos.push(0, 0, 0);
  79029. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  79030. bodyConfig.rot.push(0);
  79031. bodyConfig.rot.push(0);
  79032. bodyConfig.rot.push(0);
  79033. bodyConfig.rotShape.push(rot.x * radToDeg);
  79034. bodyConfig.rotShape.push(rot.y * radToDeg);
  79035. bodyConfig.rotShape.push(rot.z * radToDeg);
  79036. }
  79037. // register mesh
  79038. switch (i.type) {
  79039. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79040. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  79041. case BABYLON.PhysicsImpostor.SphereImpostor:
  79042. var radiusX = extendSize.x;
  79043. var radiusY = extendSize.y;
  79044. var radiusZ = extendSize.z;
  79045. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79046. bodyConfig.type.push('sphere');
  79047. //due to the way oimo works with compounds, add 3 times
  79048. bodyConfig.size.push(size);
  79049. bodyConfig.size.push(size);
  79050. bodyConfig.size.push(size);
  79051. break;
  79052. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79053. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79054. var sizeY = checkWithEpsilon_1(extendSize.y);
  79055. bodyConfig.type.push('cylinder');
  79056. bodyConfig.size.push(sizeX);
  79057. bodyConfig.size.push(sizeY);
  79058. //due to the way oimo works with compounds, add one more value.
  79059. bodyConfig.size.push(sizeY);
  79060. break;
  79061. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79062. case BABYLON.PhysicsImpostor.BoxImpostor:
  79063. default:
  79064. var sizeX = checkWithEpsilon_1(extendSize.x);
  79065. var sizeY = checkWithEpsilon_1(extendSize.y);
  79066. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79067. bodyConfig.type.push('box');
  79068. //if (i === impostor) {
  79069. bodyConfig.size.push(sizeX);
  79070. bodyConfig.size.push(sizeY);
  79071. bodyConfig.size.push(sizeZ);
  79072. //} else {
  79073. // bodyConfig.size.push(0,0,0);
  79074. //}
  79075. break;
  79076. }
  79077. //actually not needed, but hey...
  79078. i.object.rotationQuaternion = oldQuaternion;
  79079. });
  79080. impostor.physicsBody = this.world.add(bodyConfig);
  79081. }
  79082. else {
  79083. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79084. }
  79085. impostor.setDeltaPosition(this._tmpPositionVector);
  79086. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79087. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79088. };
  79089. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79090. //impostor.physicsBody.dispose();
  79091. //Same as : (older oimo versions)
  79092. this.world.removeRigidBody(impostor.physicsBody);
  79093. };
  79094. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79095. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79096. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79097. if (!mainBody || !connectedBody) {
  79098. return;
  79099. }
  79100. var jointData = impostorJoint.joint.jointData;
  79101. var options = jointData.nativeParams || {};
  79102. var type;
  79103. var nativeJointData = {
  79104. body1: mainBody,
  79105. body2: connectedBody,
  79106. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79107. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79108. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79109. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79110. min: options.min,
  79111. max: options.max,
  79112. collision: options.collision || jointData.collision,
  79113. spring: options.spring,
  79114. //supporting older version of Oimo
  79115. world: this.world
  79116. };
  79117. switch (impostorJoint.joint.type) {
  79118. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79119. type = "jointBall";
  79120. break;
  79121. case BABYLON.PhysicsJoint.SpringJoint:
  79122. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79123. var springData = jointData;
  79124. nativeJointData.min = springData.length || nativeJointData.min;
  79125. //Max should also be set, just make sure it is at least min
  79126. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79127. case BABYLON.PhysicsJoint.DistanceJoint:
  79128. type = "jointDistance";
  79129. nativeJointData.max = jointData.maxDistance;
  79130. break;
  79131. case BABYLON.PhysicsJoint.PrismaticJoint:
  79132. type = "jointPrisme";
  79133. break;
  79134. case BABYLON.PhysicsJoint.SliderJoint:
  79135. type = "jointSlide";
  79136. break;
  79137. case BABYLON.PhysicsJoint.WheelJoint:
  79138. type = "jointWheel";
  79139. break;
  79140. case BABYLON.PhysicsJoint.HingeJoint:
  79141. default:
  79142. type = "jointHinge";
  79143. break;
  79144. }
  79145. nativeJointData.type = type;
  79146. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  79147. };
  79148. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79149. //Bug in Oimo prevents us from disposing a joint in the playground
  79150. //joint.joint.physicsJoint.dispose();
  79151. //So we will bruteforce it!
  79152. try {
  79153. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79154. }
  79155. catch (e) {
  79156. BABYLON.Tools.Warn(e);
  79157. }
  79158. };
  79159. OimoJSPlugin.prototype.isSupported = function () {
  79160. return this.BJSOIMO !== undefined;
  79161. };
  79162. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79163. if (!impostor.physicsBody.sleeping) {
  79164. //TODO check that
  79165. /*if (impostor.physicsBody.shapes.next) {
  79166. var parentShape = this._getLastShape(impostor.physicsBody);
  79167. impostor.object.position.copyFrom(parentShape.position);
  79168. console.log(parentShape.position);
  79169. } else {*/
  79170. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79171. //}
  79172. if (impostor.object.rotationQuaternion) {
  79173. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79174. }
  79175. }
  79176. };
  79177. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79178. var body = impostor.physicsBody;
  79179. body.position.copy(newPosition);
  79180. body.orientation.copy(newRotation);
  79181. body.syncShapes();
  79182. body.awake();
  79183. };
  79184. /*private _getLastShape(body: any): any {
  79185. var lastShape = body.shapes;
  79186. while (lastShape.next) {
  79187. lastShape = lastShape.next;
  79188. }
  79189. return lastShape;
  79190. }*/
  79191. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79192. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79193. };
  79194. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79195. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79196. };
  79197. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79198. var v = impostor.physicsBody.linearVelocity;
  79199. if (!v) {
  79200. return null;
  79201. }
  79202. return new BABYLON.Vector3(v.x, v.y, v.z);
  79203. };
  79204. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79205. var v = impostor.physicsBody.angularVelocity;
  79206. if (!v) {
  79207. return null;
  79208. }
  79209. return new BABYLON.Vector3(v.x, v.y, v.z);
  79210. };
  79211. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79212. var staticBody = mass === 0;
  79213. //this will actually set the body's density and not its mass.
  79214. //But this is how oimo treats the mass variable.
  79215. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79216. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79217. };
  79218. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79219. return impostor.physicsBody.shapes.density;
  79220. };
  79221. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79222. return impostor.physicsBody.shapes.friction;
  79223. };
  79224. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79225. impostor.physicsBody.shapes.friction = friction;
  79226. };
  79227. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79228. return impostor.physicsBody.shapes.restitution;
  79229. };
  79230. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79231. impostor.physicsBody.shapes.restitution = restitution;
  79232. };
  79233. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79234. impostor.physicsBody.sleep();
  79235. };
  79236. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79237. impostor.physicsBody.awake();
  79238. };
  79239. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79240. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79241. if (minDistance !== void 0) {
  79242. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79243. }
  79244. };
  79245. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79246. //TODO separate rotational and transational motors.
  79247. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79248. if (motor) {
  79249. motor.setMotor(speed, maxForce);
  79250. }
  79251. };
  79252. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79253. //TODO separate rotational and transational motors.
  79254. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79255. if (motor) {
  79256. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79257. }
  79258. };
  79259. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79260. var body = impostor.physicsBody;
  79261. mesh.position.x = body.position.x;
  79262. mesh.position.y = body.position.y;
  79263. mesh.position.z = body.position.z;
  79264. if (mesh.rotationQuaternion) {
  79265. mesh.rotationQuaternion.x = body.orientation.x;
  79266. mesh.rotationQuaternion.y = body.orientation.y;
  79267. mesh.rotationQuaternion.z = body.orientation.z;
  79268. mesh.rotationQuaternion.w = body.orientation.s;
  79269. }
  79270. };
  79271. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79272. return impostor.physicsBody.shapes.radius;
  79273. };
  79274. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79275. var shape = impostor.physicsBody.shapes;
  79276. result.x = shape.halfWidth * 2;
  79277. result.y = shape.halfHeight * 2;
  79278. result.z = shape.halfDepth * 2;
  79279. };
  79280. OimoJSPlugin.prototype.dispose = function () {
  79281. this.world.clear();
  79282. };
  79283. return OimoJSPlugin;
  79284. }());
  79285. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79286. })(BABYLON || (BABYLON = {}));
  79287. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79288. "use strict";
  79289. var BABYLON;
  79290. (function (BABYLON) {
  79291. /*
  79292. * Based on jsTGALoader - Javascript loader for TGA file
  79293. * By Vincent Thibault
  79294. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79295. */
  79296. var TGATools = /** @class */ (function () {
  79297. function TGATools() {
  79298. }
  79299. TGATools.GetTGAHeader = function (data) {
  79300. var offset = 0;
  79301. var header = {
  79302. id_length: data[offset++],
  79303. colormap_type: data[offset++],
  79304. image_type: data[offset++],
  79305. colormap_index: data[offset++] | data[offset++] << 8,
  79306. colormap_length: data[offset++] | data[offset++] << 8,
  79307. colormap_size: data[offset++],
  79308. origin: [
  79309. data[offset++] | data[offset++] << 8,
  79310. data[offset++] | data[offset++] << 8
  79311. ],
  79312. width: data[offset++] | data[offset++] << 8,
  79313. height: data[offset++] | data[offset++] << 8,
  79314. pixel_size: data[offset++],
  79315. flags: data[offset++]
  79316. };
  79317. return header;
  79318. };
  79319. TGATools.UploadContent = function (gl, data) {
  79320. // Not enough data to contain header ?
  79321. if (data.length < 19) {
  79322. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79323. return;
  79324. }
  79325. // Read Header
  79326. var offset = 18;
  79327. var header = TGATools.GetTGAHeader(data);
  79328. // Assume it's a valid Targa file.
  79329. if (header.id_length + offset > data.length) {
  79330. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79331. return;
  79332. }
  79333. // Skip not needed data
  79334. offset += header.id_length;
  79335. var use_rle = false;
  79336. var use_pal = false;
  79337. var use_grey = false;
  79338. // Get some informations.
  79339. switch (header.image_type) {
  79340. case TGATools._TYPE_RLE_INDEXED:
  79341. use_rle = true;
  79342. case TGATools._TYPE_INDEXED:
  79343. use_pal = true;
  79344. break;
  79345. case TGATools._TYPE_RLE_RGB:
  79346. use_rle = true;
  79347. case TGATools._TYPE_RGB:
  79348. // use_rgb = true;
  79349. break;
  79350. case TGATools._TYPE_RLE_GREY:
  79351. use_rle = true;
  79352. case TGATools._TYPE_GREY:
  79353. use_grey = true;
  79354. break;
  79355. }
  79356. var pixel_data;
  79357. // var numAlphaBits = header.flags & 0xf;
  79358. var pixel_size = header.pixel_size >> 3;
  79359. var pixel_total = header.width * header.height * pixel_size;
  79360. // Read palettes
  79361. var palettes;
  79362. if (use_pal) {
  79363. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79364. }
  79365. // Read LRE
  79366. if (use_rle) {
  79367. pixel_data = new Uint8Array(pixel_total);
  79368. var c, count, i;
  79369. var localOffset = 0;
  79370. var pixels = new Uint8Array(pixel_size);
  79371. while (offset < pixel_total && localOffset < pixel_total) {
  79372. c = data[offset++];
  79373. count = (c & 0x7f) + 1;
  79374. // RLE pixels
  79375. if (c & 0x80) {
  79376. // Bind pixel tmp array
  79377. for (i = 0; i < pixel_size; ++i) {
  79378. pixels[i] = data[offset++];
  79379. }
  79380. // Copy pixel array
  79381. for (i = 0; i < count; ++i) {
  79382. pixel_data.set(pixels, localOffset + i * pixel_size);
  79383. }
  79384. localOffset += pixel_size * count;
  79385. }
  79386. else {
  79387. count *= pixel_size;
  79388. for (i = 0; i < count; ++i) {
  79389. pixel_data[localOffset + i] = data[offset++];
  79390. }
  79391. localOffset += count;
  79392. }
  79393. }
  79394. }
  79395. else {
  79396. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79397. }
  79398. // Load to texture
  79399. var x_start, y_start, x_step, y_step, y_end, x_end;
  79400. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79401. default:
  79402. case TGATools._ORIGIN_UL:
  79403. x_start = 0;
  79404. x_step = 1;
  79405. x_end = header.width;
  79406. y_start = 0;
  79407. y_step = 1;
  79408. y_end = header.height;
  79409. break;
  79410. case TGATools._ORIGIN_BL:
  79411. x_start = 0;
  79412. x_step = 1;
  79413. x_end = header.width;
  79414. y_start = header.height - 1;
  79415. y_step = -1;
  79416. y_end = -1;
  79417. break;
  79418. case TGATools._ORIGIN_UR:
  79419. x_start = header.width - 1;
  79420. x_step = -1;
  79421. x_end = -1;
  79422. y_start = 0;
  79423. y_step = 1;
  79424. y_end = header.height;
  79425. break;
  79426. case TGATools._ORIGIN_BR:
  79427. x_start = header.width - 1;
  79428. x_step = -1;
  79429. x_end = -1;
  79430. y_start = header.height - 1;
  79431. y_step = -1;
  79432. y_end = -1;
  79433. break;
  79434. }
  79435. // Load the specify method
  79436. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79437. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79438. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79439. };
  79440. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79441. var image = pixel_data, colormap = palettes;
  79442. var width = header.width, height = header.height;
  79443. var color, i = 0, x, y;
  79444. var imageData = new Uint8Array(width * height * 4);
  79445. for (y = y_start; y !== y_end; y += y_step) {
  79446. for (x = x_start; x !== x_end; x += x_step, i++) {
  79447. color = image[i];
  79448. imageData[(x + width * y) * 4 + 3] = 255;
  79449. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79450. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79451. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79452. }
  79453. }
  79454. return imageData;
  79455. };
  79456. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79457. var image = pixel_data;
  79458. var width = header.width, height = header.height;
  79459. var color, i = 0, x, y;
  79460. var imageData = new Uint8Array(width * height * 4);
  79461. for (y = y_start; y !== y_end; y += y_step) {
  79462. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79463. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79464. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79465. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79466. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79467. imageData[(x + width * y) * 4 + 0] = r;
  79468. imageData[(x + width * y) * 4 + 1] = g;
  79469. imageData[(x + width * y) * 4 + 2] = b;
  79470. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79471. }
  79472. }
  79473. return imageData;
  79474. };
  79475. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79476. var image = pixel_data;
  79477. var width = header.width, height = header.height;
  79478. var i = 0, x, y;
  79479. var imageData = new Uint8Array(width * height * 4);
  79480. for (y = y_start; y !== y_end; y += y_step) {
  79481. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79482. imageData[(x + width * y) * 4 + 3] = 255;
  79483. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79484. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79485. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79486. }
  79487. }
  79488. return imageData;
  79489. };
  79490. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79491. var image = pixel_data;
  79492. var width = header.width, height = header.height;
  79493. var i = 0, x, y;
  79494. var imageData = new Uint8Array(width * height * 4);
  79495. for (y = y_start; y !== y_end; y += y_step) {
  79496. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79497. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79498. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79499. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79500. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79501. }
  79502. }
  79503. return imageData;
  79504. };
  79505. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79506. var image = pixel_data;
  79507. var width = header.width, height = header.height;
  79508. var color, i = 0, x, y;
  79509. var imageData = new Uint8Array(width * height * 4);
  79510. for (y = y_start; y !== y_end; y += y_step) {
  79511. for (x = x_start; x !== x_end; x += x_step, i++) {
  79512. color = image[i];
  79513. imageData[(x + width * y) * 4 + 0] = color;
  79514. imageData[(x + width * y) * 4 + 1] = color;
  79515. imageData[(x + width * y) * 4 + 2] = color;
  79516. imageData[(x + width * y) * 4 + 3] = 255;
  79517. }
  79518. }
  79519. return imageData;
  79520. };
  79521. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79522. var image = pixel_data;
  79523. var width = header.width, height = header.height;
  79524. var i = 0, x, y;
  79525. var imageData = new Uint8Array(width * height * 4);
  79526. for (y = y_start; y !== y_end; y += y_step) {
  79527. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79528. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79529. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79530. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79531. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79532. }
  79533. }
  79534. return imageData;
  79535. };
  79536. //private static _TYPE_NO_DATA = 0;
  79537. TGATools._TYPE_INDEXED = 1;
  79538. TGATools._TYPE_RGB = 2;
  79539. TGATools._TYPE_GREY = 3;
  79540. TGATools._TYPE_RLE_INDEXED = 9;
  79541. TGATools._TYPE_RLE_RGB = 10;
  79542. TGATools._TYPE_RLE_GREY = 11;
  79543. TGATools._ORIGIN_MASK = 0x30;
  79544. TGATools._ORIGIN_SHIFT = 0x04;
  79545. TGATools._ORIGIN_BL = 0x00;
  79546. TGATools._ORIGIN_BR = 0x01;
  79547. TGATools._ORIGIN_UL = 0x02;
  79548. TGATools._ORIGIN_UR = 0x03;
  79549. return TGATools;
  79550. }());
  79551. BABYLON.TGATools = TGATools;
  79552. })(BABYLON || (BABYLON = {}));
  79553. //# sourceMappingURL=babylon.tga.js.map
  79554. "use strict";
  79555. var BABYLON;
  79556. (function (BABYLON) {
  79557. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79558. // All values and structures referenced from:
  79559. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79560. var DDS_MAGIC = 0x20534444;
  79561. var
  79562. //DDSD_CAPS = 0x1,
  79563. //DDSD_HEIGHT = 0x2,
  79564. //DDSD_WIDTH = 0x4,
  79565. //DDSD_PITCH = 0x8,
  79566. //DDSD_PIXELFORMAT = 0x1000,
  79567. DDSD_MIPMAPCOUNT = 0x20000;
  79568. //DDSD_LINEARSIZE = 0x80000,
  79569. //DDSD_DEPTH = 0x800000;
  79570. // var DDSCAPS_COMPLEX = 0x8,
  79571. // DDSCAPS_MIPMAP = 0x400000,
  79572. // DDSCAPS_TEXTURE = 0x1000;
  79573. var DDSCAPS2_CUBEMAP = 0x200;
  79574. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79575. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79576. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79577. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79578. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79579. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79580. // DDSCAPS2_VOLUME = 0x200000;
  79581. var
  79582. //DDPF_ALPHAPIXELS = 0x1,
  79583. //DDPF_ALPHA = 0x2,
  79584. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79585. //DDPF_YUV = 0x200,
  79586. DDPF_LUMINANCE = 0x20000;
  79587. function FourCCToInt32(value) {
  79588. return value.charCodeAt(0) +
  79589. (value.charCodeAt(1) << 8) +
  79590. (value.charCodeAt(2) << 16) +
  79591. (value.charCodeAt(3) << 24);
  79592. }
  79593. function Int32ToFourCC(value) {
  79594. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79595. }
  79596. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79597. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79598. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79599. var FOURCC_DX10 = FourCCToInt32("DX10");
  79600. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79601. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79602. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79603. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79604. var headerLengthInt = 31; // The header length in 32 bit ints
  79605. // Offsets into the header array
  79606. var off_magic = 0;
  79607. var off_size = 1;
  79608. var off_flags = 2;
  79609. var off_height = 3;
  79610. var off_width = 4;
  79611. var off_mipmapCount = 7;
  79612. var off_pfFlags = 20;
  79613. var off_pfFourCC = 21;
  79614. var off_RGBbpp = 22;
  79615. var off_RMask = 23;
  79616. var off_GMask = 24;
  79617. var off_BMask = 25;
  79618. var off_AMask = 26;
  79619. // var off_caps1 = 27;
  79620. var off_caps2 = 28;
  79621. // var off_caps3 = 29;
  79622. // var off_caps4 = 30;
  79623. var off_dxgiFormat = 32;
  79624. ;
  79625. var DDSTools = /** @class */ (function () {
  79626. function DDSTools() {
  79627. }
  79628. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79629. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79630. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79631. var mipmapCount = 1;
  79632. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79633. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79634. }
  79635. var fourCC = header[off_pfFourCC];
  79636. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79637. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79638. switch (fourCC) {
  79639. case FOURCC_D3DFMT_R16G16B16A16F:
  79640. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79641. break;
  79642. case FOURCC_D3DFMT_R32G32B32A32F:
  79643. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79644. break;
  79645. case FOURCC_DX10:
  79646. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79647. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79648. break;
  79649. }
  79650. }
  79651. return {
  79652. width: header[off_width],
  79653. height: header[off_height],
  79654. mipmapCount: mipmapCount,
  79655. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79656. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79657. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79658. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79659. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79660. dxgiFormat: dxgiFormat,
  79661. textureType: textureType
  79662. };
  79663. };
  79664. DDSTools._ToHalfFloat = function (value) {
  79665. if (!DDSTools._FloatView) {
  79666. DDSTools._FloatView = new Float32Array(1);
  79667. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79668. }
  79669. DDSTools._FloatView[0] = value;
  79670. var x = DDSTools._Int32View[0];
  79671. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79672. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79673. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79674. /* If zero, or denormal, or exponent underflows too much for a denormal
  79675. * half, return signed zero. */
  79676. if (e < 103) {
  79677. return bits;
  79678. }
  79679. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79680. if (e > 142) {
  79681. bits |= 0x7c00;
  79682. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79683. * not Inf, so make sure we set one mantissa bit too. */
  79684. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79685. return bits;
  79686. }
  79687. /* If exponent underflows but not too much, return a denormal */
  79688. if (e < 113) {
  79689. m |= 0x0800;
  79690. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79691. * to 1, which is OK. */
  79692. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79693. return bits;
  79694. }
  79695. bits |= ((e - 112) << 10) | (m >> 1);
  79696. bits += m & 1;
  79697. return bits;
  79698. };
  79699. DDSTools._FromHalfFloat = function (value) {
  79700. var s = (value & 0x8000) >> 15;
  79701. var e = (value & 0x7C00) >> 10;
  79702. var f = value & 0x03FF;
  79703. if (e === 0) {
  79704. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  79705. }
  79706. else if (e == 0x1F) {
  79707. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79708. }
  79709. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79710. };
  79711. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79712. var destArray = new Float32Array(dataLength);
  79713. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79714. var index = 0;
  79715. for (var y = 0; y < height; y++) {
  79716. for (var x = 0; x < width; x++) {
  79717. var srcPos = (x + y * width) * 4;
  79718. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  79719. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  79720. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  79721. if (DDSTools.StoreLODInAlphaChannel) {
  79722. destArray[index + 3] = lod;
  79723. }
  79724. else {
  79725. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  79726. }
  79727. index += 4;
  79728. }
  79729. }
  79730. return destArray;
  79731. };
  79732. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79733. if (DDSTools.StoreLODInAlphaChannel) {
  79734. var destArray = new Uint16Array(dataLength);
  79735. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79736. var index = 0;
  79737. for (var y = 0; y < height; y++) {
  79738. for (var x = 0; x < width; x++) {
  79739. var srcPos = (x + y * width) * 4;
  79740. destArray[index] = srcData[srcPos];
  79741. destArray[index + 1] = srcData[srcPos + 1];
  79742. destArray[index + 2] = srcData[srcPos + 2];
  79743. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  79744. index += 4;
  79745. }
  79746. }
  79747. return destArray;
  79748. }
  79749. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  79750. };
  79751. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79752. if (DDSTools.StoreLODInAlphaChannel) {
  79753. var destArray = new Float32Array(dataLength);
  79754. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79755. var index = 0;
  79756. for (var y = 0; y < height; y++) {
  79757. for (var x = 0; x < width; x++) {
  79758. var srcPos = (x + y * width) * 4;
  79759. destArray[index] = srcData[srcPos];
  79760. destArray[index + 1] = srcData[srcPos + 1];
  79761. destArray[index + 2] = srcData[srcPos + 2];
  79762. destArray[index + 3] = lod;
  79763. index += 4;
  79764. }
  79765. }
  79766. return destArray;
  79767. }
  79768. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  79769. };
  79770. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79771. var destArray = new Uint8Array(dataLength);
  79772. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79773. var index = 0;
  79774. for (var y = 0; y < height; y++) {
  79775. for (var x = 0; x < width; x++) {
  79776. var srcPos = (x + y * width) * 4;
  79777. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  79778. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  79779. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  79780. if (DDSTools.StoreLODInAlphaChannel) {
  79781. destArray[index + 3] = lod;
  79782. }
  79783. else {
  79784. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79785. }
  79786. index += 4;
  79787. }
  79788. }
  79789. return destArray;
  79790. };
  79791. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79792. var destArray = new Uint8Array(dataLength);
  79793. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79794. var index = 0;
  79795. for (var y = 0; y < height; y++) {
  79796. for (var x = 0; x < width; x++) {
  79797. var srcPos = (x + y * width) * 4;
  79798. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79799. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79800. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79801. if (DDSTools.StoreLODInAlphaChannel) {
  79802. destArray[index + 3] = lod;
  79803. }
  79804. else {
  79805. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79806. }
  79807. index += 4;
  79808. }
  79809. }
  79810. return destArray;
  79811. };
  79812. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79813. var byteArray = new Uint8Array(dataLength);
  79814. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79815. var index = 0;
  79816. for (var y = 0; y < height; y++) {
  79817. for (var x = 0; x < width; x++) {
  79818. var srcPos = (x + y * width) * 4;
  79819. byteArray[index] = srcData[srcPos + rOffset];
  79820. byteArray[index + 1] = srcData[srcPos + gOffset];
  79821. byteArray[index + 2] = srcData[srcPos + bOffset];
  79822. byteArray[index + 3] = srcData[srcPos + aOffset];
  79823. index += 4;
  79824. }
  79825. }
  79826. return byteArray;
  79827. };
  79828. DDSTools._ExtractLongWordOrder = function (value) {
  79829. if (value === 0 || value === 255 || value === -16777216) {
  79830. return 0;
  79831. }
  79832. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79833. };
  79834. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79835. var byteArray = new Uint8Array(dataLength);
  79836. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79837. var index = 0;
  79838. for (var y = 0; y < height; y++) {
  79839. for (var x = 0; x < width; x++) {
  79840. var srcPos = (x + y * width) * 3;
  79841. byteArray[index] = srcData[srcPos + rOffset];
  79842. byteArray[index + 1] = srcData[srcPos + gOffset];
  79843. byteArray[index + 2] = srcData[srcPos + bOffset];
  79844. index += 3;
  79845. }
  79846. }
  79847. return byteArray;
  79848. };
  79849. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79850. var byteArray = new Uint8Array(dataLength);
  79851. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79852. var index = 0;
  79853. for (var y = 0; y < height; y++) {
  79854. for (var x = 0; x < width; x++) {
  79855. var srcPos = (x + y * width);
  79856. byteArray[index] = srcData[srcPos];
  79857. index++;
  79858. }
  79859. }
  79860. return byteArray;
  79861. };
  79862. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79863. if (lodIndex === void 0) { lodIndex = -1; }
  79864. var ext = engine.getCaps().s3tc;
  79865. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79866. var fourCC, width, height, dataLength = 0, dataOffset;
  79867. var byteArray, mipmapCount, mip;
  79868. var internalFormat = 0;
  79869. var format = 0;
  79870. var blockBytes = 1;
  79871. if (header[off_magic] !== DDS_MAGIC) {
  79872. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79873. return;
  79874. }
  79875. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79876. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79877. return;
  79878. }
  79879. if (info.isCompressed && !ext) {
  79880. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79881. return;
  79882. }
  79883. var bpp = header[off_RGBbpp];
  79884. dataOffset = header[off_size] + 4;
  79885. var computeFormats = false;
  79886. if (info.isFourCC) {
  79887. fourCC = header[off_pfFourCC];
  79888. switch (fourCC) {
  79889. case FOURCC_DXT1:
  79890. blockBytes = 8;
  79891. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79892. break;
  79893. case FOURCC_DXT3:
  79894. blockBytes = 16;
  79895. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79896. break;
  79897. case FOURCC_DXT5:
  79898. blockBytes = 16;
  79899. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79900. break;
  79901. case FOURCC_D3DFMT_R16G16B16A16F:
  79902. computeFormats = true;
  79903. break;
  79904. case FOURCC_D3DFMT_R32G32B32A32F:
  79905. computeFormats = true;
  79906. break;
  79907. case FOURCC_DX10:
  79908. // There is an additionnal header so dataOffset need to be changed
  79909. dataOffset += 5 * 4; // 5 uints
  79910. var supported = false;
  79911. switch (info.dxgiFormat) {
  79912. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79913. computeFormats = true;
  79914. supported = true;
  79915. break;
  79916. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79917. info.isRGB = true;
  79918. info.isFourCC = false;
  79919. bpp = 32;
  79920. supported = true;
  79921. break;
  79922. }
  79923. if (supported) {
  79924. break;
  79925. }
  79926. default:
  79927. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79928. return;
  79929. }
  79930. }
  79931. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79932. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79933. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79934. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79935. if (computeFormats) {
  79936. format = engine._getWebGLTextureType(info.textureType);
  79937. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79938. }
  79939. mipmapCount = 1;
  79940. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79941. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79942. }
  79943. for (var face = 0; face < faces; face++) {
  79944. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79945. width = header[off_width];
  79946. height = header[off_height];
  79947. for (mip = 0; mip < mipmapCount; ++mip) {
  79948. if (lodIndex === -1 || lodIndex === mip) {
  79949. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79950. var i = (lodIndex === -1) ? mip : 0;
  79951. if (!info.isCompressed && info.isFourCC) {
  79952. dataLength = width * height * 4;
  79953. var floatArray = null;
  79954. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79955. if (bpp === 128) {
  79956. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79957. }
  79958. else if (bpp === 64) {
  79959. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79960. }
  79961. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79962. format = engine._getWebGLTextureType(info.textureType);
  79963. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79964. }
  79965. else {
  79966. if (bpp === 128) {
  79967. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79968. }
  79969. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79970. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79971. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79972. format = engine._getWebGLTextureType(info.textureType);
  79973. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79974. }
  79975. else {
  79976. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79977. }
  79978. }
  79979. if (floatArray) {
  79980. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79981. }
  79982. }
  79983. else if (info.isRGB) {
  79984. if (bpp === 24) {
  79985. dataLength = width * height * 3;
  79986. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79987. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79988. }
  79989. else {
  79990. dataLength = width * height * 4;
  79991. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79992. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79993. }
  79994. }
  79995. else if (info.isLuminance) {
  79996. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79997. var unpaddedRowSize = width;
  79998. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79999. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  80000. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  80001. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  80002. }
  80003. else {
  80004. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  80005. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  80006. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  80007. }
  80008. }
  80009. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  80010. width *= 0.5;
  80011. height *= 0.5;
  80012. width = Math.max(1.0, width);
  80013. height = Math.max(1.0, height);
  80014. }
  80015. if (currentFace !== undefined) {
  80016. // Loading a single face
  80017. break;
  80018. }
  80019. }
  80020. };
  80021. DDSTools.StoreLODInAlphaChannel = false;
  80022. return DDSTools;
  80023. }());
  80024. BABYLON.DDSTools = DDSTools;
  80025. })(BABYLON || (BABYLON = {}));
  80026. //# sourceMappingURL=babylon.dds.js.map
  80027. "use strict";
  80028. var BABYLON;
  80029. (function (BABYLON) {
  80030. /**
  80031. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  80032. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  80033. */
  80034. var KhronosTextureContainer = /** @class */ (function () {
  80035. /**
  80036. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80037. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80038. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80039. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80040. */
  80041. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80042. this.arrayBuffer = arrayBuffer;
  80043. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80044. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80045. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80046. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80047. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80048. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80049. BABYLON.Tools.Error("texture missing KTX identifier");
  80050. return;
  80051. }
  80052. // load the reset of the header in native 32 bit int
  80053. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80054. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80055. var oppositeEndianess = header[0] === 0x01020304;
  80056. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80057. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80058. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80059. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80060. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80061. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80062. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80063. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80064. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80065. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80066. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80067. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80068. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80069. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80070. if (this.glType !== 0) {
  80071. BABYLON.Tools.Error("only compressed formats currently supported");
  80072. return;
  80073. }
  80074. else {
  80075. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80076. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80077. }
  80078. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80079. BABYLON.Tools.Error("only 2D textures currently supported");
  80080. return;
  80081. }
  80082. if (this.numberOfArrayElements !== 0) {
  80083. BABYLON.Tools.Error("texture arrays not currently supported");
  80084. return;
  80085. }
  80086. if (this.numberOfFaces !== facesExpected) {
  80087. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80088. return;
  80089. }
  80090. // we now have a completely validated file, so could use existence of loadType as success
  80091. // would need to make this more elaborate & adjust checks above to support more than one load type
  80092. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80093. }
  80094. // not as fast hardware based, but will probably never need to use
  80095. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80096. return ((val & 0xFF) << 24)
  80097. | ((val & 0xFF00) << 8)
  80098. | ((val >> 8) & 0xFF00)
  80099. | ((val >> 24) & 0xFF);
  80100. };
  80101. /**
  80102. * It is assumed that the texture has already been created & is currently bound
  80103. */
  80104. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80105. switch (this.loadType) {
  80106. case KhronosTextureContainer.COMPRESSED_2D:
  80107. this._upload2DCompressedLevels(gl, loadMipmaps);
  80108. break;
  80109. case KhronosTextureContainer.TEX_2D:
  80110. case KhronosTextureContainer.COMPRESSED_3D:
  80111. case KhronosTextureContainer.TEX_3D:
  80112. }
  80113. };
  80114. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80115. // initialize width & height for level 1
  80116. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80117. var width = this.pixelWidth;
  80118. var height = this.pixelHeight;
  80119. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80120. for (var level = 0; level < mipmapCount; level++) {
  80121. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80122. for (var face = 0; face < this.numberOfFaces; face++) {
  80123. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80124. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80125. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80126. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80127. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80128. }
  80129. width = Math.max(1.0, width * 0.5);
  80130. height = Math.max(1.0, height * 0.5);
  80131. }
  80132. };
  80133. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80134. // load types
  80135. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80136. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80137. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80138. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80139. return KhronosTextureContainer;
  80140. }());
  80141. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80142. })(BABYLON || (BABYLON = {}));
  80143. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80144. "use strict";
  80145. var BABYLON;
  80146. (function (BABYLON) {
  80147. var Debug = /** @class */ (function () {
  80148. function Debug() {
  80149. }
  80150. Debug.AxesViewer = /** @class */ (function () {
  80151. function AxesViewer(scene, scaleLines) {
  80152. if (scaleLines === void 0) { scaleLines = 1; }
  80153. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80154. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80155. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80156. this.scaleLines = 1;
  80157. this.scaleLines = scaleLines;
  80158. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80159. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80160. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80161. this._xmesh.renderingGroupId = 2;
  80162. this._ymesh.renderingGroupId = 2;
  80163. this._zmesh.renderingGroupId = 2;
  80164. this._xmesh.material.checkReadyOnlyOnce = true;
  80165. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80166. this._ymesh.material.checkReadyOnlyOnce = true;
  80167. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80168. this._zmesh.material.checkReadyOnlyOnce = true;
  80169. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80170. this.scene = scene;
  80171. }
  80172. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80173. var scaleLines = this.scaleLines;
  80174. if (this._xmesh) {
  80175. this._xmesh.position.copyFrom(position);
  80176. }
  80177. if (this._ymesh) {
  80178. this._ymesh.position.copyFrom(position);
  80179. }
  80180. if (this._zmesh) {
  80181. this._zmesh.position.copyFrom(position);
  80182. }
  80183. var point2 = this._xline[1];
  80184. point2.x = xaxis.x * scaleLines;
  80185. point2.y = xaxis.y * scaleLines;
  80186. point2.z = xaxis.z * scaleLines;
  80187. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80188. point2 = this._yline[1];
  80189. point2.x = yaxis.x * scaleLines;
  80190. point2.y = yaxis.y * scaleLines;
  80191. point2.z = yaxis.z * scaleLines;
  80192. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80193. point2 = this._zline[1];
  80194. point2.x = zaxis.x * scaleLines;
  80195. point2.y = zaxis.y * scaleLines;
  80196. point2.z = zaxis.z * scaleLines;
  80197. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80198. };
  80199. AxesViewer.prototype.dispose = function () {
  80200. if (this._xmesh) {
  80201. this._xmesh.dispose();
  80202. }
  80203. if (this._ymesh) {
  80204. this._ymesh.dispose();
  80205. }
  80206. if (this._zmesh) {
  80207. this._zmesh.dispose();
  80208. }
  80209. this._xmesh = null;
  80210. this._ymesh = null;
  80211. this._zmesh = null;
  80212. this.scene = null;
  80213. };
  80214. return AxesViewer;
  80215. }());
  80216. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80217. __extends(BoneAxesViewer, _super);
  80218. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80219. if (scaleLines === void 0) { scaleLines = 1; }
  80220. var _this = _super.call(this, scene, scaleLines) || this;
  80221. _this.pos = BABYLON.Vector3.Zero();
  80222. _this.xaxis = BABYLON.Vector3.Zero();
  80223. _this.yaxis = BABYLON.Vector3.Zero();
  80224. _this.zaxis = BABYLON.Vector3.Zero();
  80225. _this.mesh = mesh;
  80226. _this.bone = bone;
  80227. return _this;
  80228. }
  80229. BoneAxesViewer.prototype.update = function () {
  80230. if (!this.mesh || !this.bone) {
  80231. return;
  80232. }
  80233. var bone = this.bone;
  80234. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80235. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80236. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80237. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80238. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80239. };
  80240. BoneAxesViewer.prototype.dispose = function () {
  80241. if (this.mesh) {
  80242. this.mesh = null;
  80243. this.bone = null;
  80244. _super.prototype.dispose.call(this);
  80245. }
  80246. };
  80247. return BoneAxesViewer;
  80248. }(Debug.AxesViewer));
  80249. Debug.PhysicsViewer = /** @class */ (function () {
  80250. function PhysicsViewer(scene) {
  80251. this._impostors = [];
  80252. this._meshes = [];
  80253. this._numMeshes = 0;
  80254. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80255. var physicEngine = this._scene.getPhysicsEngine();
  80256. if (physicEngine) {
  80257. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80258. }
  80259. }
  80260. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80261. var plugin = this._physicsEnginePlugin;
  80262. for (var i = 0; i < this._numMeshes; i++) {
  80263. var impostor = this._impostors[i];
  80264. if (!impostor) {
  80265. continue;
  80266. }
  80267. if (impostor.isDisposed) {
  80268. this.hideImpostor(this._impostors[i--]);
  80269. }
  80270. else {
  80271. var mesh = this._meshes[i];
  80272. if (mesh && plugin) {
  80273. plugin.syncMeshWithImpostor(mesh, impostor);
  80274. }
  80275. }
  80276. }
  80277. };
  80278. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80279. if (!this._scene) {
  80280. return;
  80281. }
  80282. for (var i = 0; i < this._numMeshes; i++) {
  80283. if (this._impostors[i] == impostor) {
  80284. return;
  80285. }
  80286. }
  80287. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80288. if (debugMesh) {
  80289. this._impostors[this._numMeshes] = impostor;
  80290. this._meshes[this._numMeshes] = debugMesh;
  80291. if (this._numMeshes === 0) {
  80292. this._renderFunction = this._updateDebugMeshes.bind(this);
  80293. this._scene.registerBeforeRender(this._renderFunction);
  80294. }
  80295. this._numMeshes++;
  80296. }
  80297. };
  80298. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80299. if (!impostor || !this._scene) {
  80300. return;
  80301. }
  80302. var removed = false;
  80303. for (var i = 0; i < this._numMeshes; i++) {
  80304. if (this._impostors[i] == impostor) {
  80305. var mesh = this._meshes[i];
  80306. if (!mesh) {
  80307. continue;
  80308. }
  80309. this._scene.removeMesh(mesh);
  80310. mesh.dispose();
  80311. this._numMeshes--;
  80312. if (this._numMeshes > 0) {
  80313. this._meshes[i] = this._meshes[this._numMeshes];
  80314. this._impostors[i] = this._impostors[this._numMeshes];
  80315. this._meshes[this._numMeshes] = null;
  80316. this._impostors[this._numMeshes] = null;
  80317. }
  80318. else {
  80319. this._meshes[0] = null;
  80320. this._impostors[0] = null;
  80321. }
  80322. removed = true;
  80323. break;
  80324. }
  80325. }
  80326. if (removed && this._numMeshes === 0) {
  80327. this._scene.unregisterBeforeRender(this._renderFunction);
  80328. }
  80329. };
  80330. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80331. if (!this._debugMaterial) {
  80332. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80333. this._debugMaterial.wireframe = true;
  80334. }
  80335. return this._debugMaterial;
  80336. };
  80337. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80338. if (!this._debugBoxMesh) {
  80339. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80340. this._debugBoxMesh.renderingGroupId = 1;
  80341. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80342. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80343. scene.removeMesh(this._debugBoxMesh);
  80344. }
  80345. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80346. };
  80347. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80348. if (!this._debugSphereMesh) {
  80349. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80350. this._debugSphereMesh.renderingGroupId = 1;
  80351. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80352. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80353. scene.removeMesh(this._debugSphereMesh);
  80354. }
  80355. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80356. };
  80357. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80358. var mesh = null;
  80359. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80360. mesh = this._getDebugBoxMesh(scene);
  80361. impostor.getBoxSizeToRef(mesh.scaling);
  80362. }
  80363. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80364. mesh = this._getDebugSphereMesh(scene);
  80365. var radius = impostor.getRadius();
  80366. mesh.scaling.x = radius * 2;
  80367. mesh.scaling.y = radius * 2;
  80368. mesh.scaling.z = radius * 2;
  80369. }
  80370. return mesh;
  80371. };
  80372. PhysicsViewer.prototype.dispose = function () {
  80373. for (var i = 0; i < this._numMeshes; i++) {
  80374. this.hideImpostor(this._impostors[i]);
  80375. }
  80376. if (this._debugBoxMesh) {
  80377. this._debugBoxMesh.dispose();
  80378. }
  80379. if (this._debugSphereMesh) {
  80380. this._debugSphereMesh.dispose();
  80381. }
  80382. if (this._debugMaterial) {
  80383. this._debugMaterial.dispose();
  80384. }
  80385. this._impostors.length = 0;
  80386. this._scene = null;
  80387. this._physicsEnginePlugin = null;
  80388. };
  80389. return PhysicsViewer;
  80390. }());
  80391. Debug.SkeletonViewer = /** @class */ (function () {
  80392. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80393. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80394. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80395. this.skeleton = skeleton;
  80396. this.mesh = mesh;
  80397. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80398. this.renderingGroupId = renderingGroupId;
  80399. this.color = BABYLON.Color3.White();
  80400. this._debugLines = new Array();
  80401. this._isEnabled = false;
  80402. this._scene = scene;
  80403. this.update();
  80404. this._renderFunction = this.update.bind(this);
  80405. }
  80406. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80407. get: function () {
  80408. return this._isEnabled;
  80409. },
  80410. set: function (value) {
  80411. if (this._isEnabled === value) {
  80412. return;
  80413. }
  80414. this._isEnabled = value;
  80415. if (value) {
  80416. this._scene.registerBeforeRender(this._renderFunction);
  80417. }
  80418. else {
  80419. this._scene.unregisterBeforeRender(this._renderFunction);
  80420. }
  80421. },
  80422. enumerable: true,
  80423. configurable: true
  80424. });
  80425. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80426. if (x === void 0) { x = 0; }
  80427. if (y === void 0) { y = 0; }
  80428. if (z === void 0) { z = 0; }
  80429. var tmat = BABYLON.Tmp.Matrix[0];
  80430. var parentBone = bone.getParent();
  80431. tmat.copyFrom(bone.getLocalMatrix());
  80432. if (x !== 0 || y !== 0 || z !== 0) {
  80433. var tmat2 = BABYLON.Tmp.Matrix[1];
  80434. BABYLON.Matrix.IdentityToRef(tmat2);
  80435. tmat2.m[12] = x;
  80436. tmat2.m[13] = y;
  80437. tmat2.m[14] = z;
  80438. tmat2.multiplyToRef(tmat, tmat);
  80439. }
  80440. if (parentBone) {
  80441. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80442. }
  80443. tmat.multiplyToRef(meshMat, tmat);
  80444. position.x = tmat.m[12];
  80445. position.y = tmat.m[13];
  80446. position.z = tmat.m[14];
  80447. };
  80448. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80449. var len = bones.length;
  80450. var meshPos = this.mesh.position;
  80451. for (var i = 0; i < len; i++) {
  80452. var bone = bones[i];
  80453. var points = this._debugLines[i];
  80454. if (!points) {
  80455. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80456. this._debugLines[i] = points;
  80457. }
  80458. this._getBonePosition(points[0], bone, meshMat);
  80459. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80460. points[0].subtractInPlace(meshPos);
  80461. points[1].subtractInPlace(meshPos);
  80462. }
  80463. };
  80464. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80465. var len = bones.length;
  80466. var boneNum = 0;
  80467. var meshPos = this.mesh.position;
  80468. for (var i = len - 1; i >= 0; i--) {
  80469. var childBone = bones[i];
  80470. var parentBone = childBone.getParent();
  80471. if (!parentBone) {
  80472. continue;
  80473. }
  80474. var points = this._debugLines[boneNum];
  80475. if (!points) {
  80476. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80477. this._debugLines[boneNum] = points;
  80478. }
  80479. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80480. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80481. points[0].subtractInPlace(meshPos);
  80482. points[1].subtractInPlace(meshPos);
  80483. boneNum++;
  80484. }
  80485. };
  80486. SkeletonViewer.prototype.update = function () {
  80487. if (this.autoUpdateBonesMatrices) {
  80488. this.skeleton.computeAbsoluteTransforms();
  80489. }
  80490. if (this.skeleton.bones[0].length === undefined) {
  80491. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80492. }
  80493. else {
  80494. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80495. }
  80496. if (!this._debugMesh) {
  80497. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80498. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80499. }
  80500. else {
  80501. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80502. }
  80503. this._debugMesh.position.copyFrom(this.mesh.position);
  80504. this._debugMesh.color = this.color;
  80505. };
  80506. SkeletonViewer.prototype.dispose = function () {
  80507. if (this._debugMesh) {
  80508. this.isEnabled = false;
  80509. this._debugMesh.dispose();
  80510. this._debugMesh = null;
  80511. }
  80512. };
  80513. return SkeletonViewer;
  80514. }());
  80515. return Debug;
  80516. }());
  80517. BABYLON.Debug = Debug;
  80518. })(BABYLON || (BABYLON = {}));
  80519. //# sourceMappingURL=babylon.debugModules.js.map
  80520. "use strict";
  80521. var BABYLON;
  80522. (function (BABYLON) {
  80523. var RayHelper = /** @class */ (function () {
  80524. function RayHelper(ray) {
  80525. this.ray = ray;
  80526. }
  80527. RayHelper.CreateAndShow = function (ray, scene, color) {
  80528. var helper = new RayHelper(ray);
  80529. helper.show(scene, color);
  80530. return helper;
  80531. };
  80532. RayHelper.prototype.show = function (scene, color) {
  80533. if (!this._renderFunction && this.ray) {
  80534. var ray = this.ray;
  80535. this._renderFunction = this._render.bind(this);
  80536. this._scene = scene;
  80537. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80538. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80539. if (this._renderFunction) {
  80540. this._scene.registerBeforeRender(this._renderFunction);
  80541. }
  80542. }
  80543. if (color && this._renderLine) {
  80544. this._renderLine.color.copyFrom(color);
  80545. }
  80546. };
  80547. RayHelper.prototype.hide = function () {
  80548. if (this._renderFunction && this._scene) {
  80549. this._scene.unregisterBeforeRender(this._renderFunction);
  80550. this._scene = null;
  80551. this._renderFunction = null;
  80552. if (this._renderLine) {
  80553. this._renderLine.dispose();
  80554. this._renderLine = null;
  80555. }
  80556. this._renderPoints = [];
  80557. }
  80558. };
  80559. RayHelper.prototype._render = function () {
  80560. var ray = this.ray;
  80561. if (!ray) {
  80562. return;
  80563. }
  80564. var point = this._renderPoints[1];
  80565. var len = Math.min(ray.length, 1000000);
  80566. point.copyFrom(ray.direction);
  80567. point.scaleInPlace(len);
  80568. point.addInPlace(ray.origin);
  80569. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80570. };
  80571. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80572. this._attachedToMesh = mesh;
  80573. var ray = this.ray;
  80574. if (!ray) {
  80575. return;
  80576. }
  80577. if (!ray.direction) {
  80578. ray.direction = BABYLON.Vector3.Zero();
  80579. }
  80580. if (!ray.origin) {
  80581. ray.origin = BABYLON.Vector3.Zero();
  80582. }
  80583. if (length) {
  80584. ray.length = length;
  80585. }
  80586. if (!meshSpaceOrigin) {
  80587. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80588. }
  80589. if (!meshSpaceDirection) {
  80590. // -1 so that this will work with Mesh.lookAt
  80591. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80592. }
  80593. if (!this._meshSpaceDirection) {
  80594. this._meshSpaceDirection = meshSpaceDirection.clone();
  80595. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80596. }
  80597. else {
  80598. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80599. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80600. }
  80601. if (!this._updateToMeshFunction) {
  80602. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80603. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80604. }
  80605. this._updateToMesh();
  80606. };
  80607. RayHelper.prototype.detachFromMesh = function () {
  80608. if (this._attachedToMesh) {
  80609. if (this._updateToMeshFunction) {
  80610. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80611. }
  80612. this._attachedToMesh = null;
  80613. this._updateToMeshFunction = null;
  80614. }
  80615. };
  80616. RayHelper.prototype._updateToMesh = function () {
  80617. var ray = this.ray;
  80618. if (!this._attachedToMesh || !ray) {
  80619. return;
  80620. }
  80621. if (this._attachedToMesh._isDisposed) {
  80622. this.detachFromMesh();
  80623. return;
  80624. }
  80625. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80626. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80627. };
  80628. RayHelper.prototype.dispose = function () {
  80629. this.hide();
  80630. this.detachFromMesh();
  80631. this.ray = null;
  80632. };
  80633. return RayHelper;
  80634. }());
  80635. BABYLON.RayHelper = RayHelper;
  80636. })(BABYLON || (BABYLON = {}));
  80637. //# sourceMappingURL=babylon.rayHelper.js.map
  80638. "use strict";
  80639. var BABYLON;
  80640. (function (BABYLON) {
  80641. // load the inspector using require, if not present in the global namespace.
  80642. var DebugLayer = /** @class */ (function () {
  80643. function DebugLayer(scene) {
  80644. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80645. this._scene = scene;
  80646. // load inspector using require, if it doesn't exist on the global namespace.
  80647. }
  80648. /** Creates the inspector window. */
  80649. DebugLayer.prototype._createInspector = function (config) {
  80650. if (config === void 0) { config = {}; }
  80651. var popup = config.popup || false;
  80652. var initialTab = config.initialTab || 0;
  80653. var parentElement = config.parentElement || null;
  80654. if (!this._inspector) {
  80655. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80656. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80657. } // else nothing to do,; instance is already existing
  80658. };
  80659. DebugLayer.prototype.isVisible = function () {
  80660. if (!this._inspector) {
  80661. return false;
  80662. }
  80663. return true;
  80664. };
  80665. DebugLayer.prototype.hide = function () {
  80666. if (this._inspector) {
  80667. try {
  80668. this._inspector.dispose();
  80669. }
  80670. catch (e) {
  80671. // If the inspector has been removed directly from the inspector tool
  80672. }
  80673. this._inspector = null;
  80674. }
  80675. };
  80676. DebugLayer.prototype.show = function (config) {
  80677. if (config === void 0) { config = {}; }
  80678. if (typeof this.BJSINSPECTOR == 'undefined') {
  80679. // Load inspector and add it to the DOM
  80680. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80681. }
  80682. else {
  80683. // Otherwise creates the inspector
  80684. this._createInspector(config);
  80685. }
  80686. };
  80687. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80688. return DebugLayer;
  80689. }());
  80690. BABYLON.DebugLayer = DebugLayer;
  80691. })(BABYLON || (BABYLON = {}));
  80692. //# sourceMappingURL=babylon.debugLayer.js.map
  80693. "use strict";
  80694. var BABYLON;
  80695. (function (BABYLON) {
  80696. var BoundingBoxRenderer = /** @class */ (function () {
  80697. function BoundingBoxRenderer(scene) {
  80698. this.frontColor = new BABYLON.Color3(1, 1, 1);
  80699. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  80700. this.showBackLines = true;
  80701. this.renderList = new BABYLON.SmartArray(32);
  80702. this._vertexBuffers = {};
  80703. this._scene = scene;
  80704. }
  80705. BoundingBoxRenderer.prototype._prepareRessources = function () {
  80706. if (this._colorShader) {
  80707. return;
  80708. }
  80709. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80710. attributes: [BABYLON.VertexBuffer.PositionKind],
  80711. uniforms: ["world", "viewProjection", "color"]
  80712. });
  80713. var engine = this._scene.getEngine();
  80714. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80715. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80716. this._createIndexBuffer();
  80717. };
  80718. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  80719. var engine = this._scene.getEngine();
  80720. 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]);
  80721. };
  80722. BoundingBoxRenderer.prototype._rebuild = function () {
  80723. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80724. if (vb) {
  80725. vb._rebuild();
  80726. }
  80727. this._createIndexBuffer();
  80728. };
  80729. BoundingBoxRenderer.prototype.reset = function () {
  80730. this.renderList.reset();
  80731. };
  80732. BoundingBoxRenderer.prototype.render = function () {
  80733. if (this.renderList.length === 0) {
  80734. return;
  80735. }
  80736. this._prepareRessources();
  80737. if (!this._colorShader.isReady()) {
  80738. return;
  80739. }
  80740. var engine = this._scene.getEngine();
  80741. engine.setDepthWrite(false);
  80742. this._colorShader._preBind();
  80743. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  80744. var boundingBox = this.renderList.data[boundingBoxIndex];
  80745. var min = boundingBox.minimum;
  80746. var max = boundingBox.maximum;
  80747. var diff = max.subtract(min);
  80748. var median = min.add(diff.scale(0.5));
  80749. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80750. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80751. .multiply(boundingBox.getWorldMatrix());
  80752. // VBOs
  80753. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80754. if (this.showBackLines) {
  80755. // Back
  80756. engine.setDepthFunctionToGreaterOrEqual();
  80757. this._scene.resetCachedMaterial();
  80758. this._colorShader.setColor4("color", this.backColor.toColor4());
  80759. this._colorShader.bind(worldMatrix);
  80760. // Draw order
  80761. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80762. }
  80763. // Front
  80764. engine.setDepthFunctionToLess();
  80765. this._scene.resetCachedMaterial();
  80766. this._colorShader.setColor4("color", this.frontColor.toColor4());
  80767. this._colorShader.bind(worldMatrix);
  80768. // Draw order
  80769. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80770. }
  80771. this._colorShader.unbind();
  80772. engine.setDepthFunctionToLessOrEqual();
  80773. engine.setDepthWrite(true);
  80774. };
  80775. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  80776. this._prepareRessources();
  80777. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  80778. return;
  80779. }
  80780. var engine = this._scene.getEngine();
  80781. engine.setDepthWrite(false);
  80782. engine.setColorWrite(false);
  80783. this._colorShader._preBind();
  80784. var boundingBox = mesh._boundingInfo.boundingBox;
  80785. var min = boundingBox.minimum;
  80786. var max = boundingBox.maximum;
  80787. var diff = max.subtract(min);
  80788. var median = min.add(diff.scale(0.5));
  80789. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80790. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80791. .multiply(boundingBox.getWorldMatrix());
  80792. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80793. engine.setDepthFunctionToLess();
  80794. this._scene.resetCachedMaterial();
  80795. this._colorShader.bind(worldMatrix);
  80796. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80797. this._colorShader.unbind();
  80798. engine.setDepthFunctionToLessOrEqual();
  80799. engine.setDepthWrite(true);
  80800. engine.setColorWrite(true);
  80801. };
  80802. BoundingBoxRenderer.prototype.dispose = function () {
  80803. if (!this._colorShader) {
  80804. return;
  80805. }
  80806. this.renderList.dispose();
  80807. this._colorShader.dispose();
  80808. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80809. if (buffer) {
  80810. buffer.dispose();
  80811. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80812. }
  80813. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80814. };
  80815. return BoundingBoxRenderer;
  80816. }());
  80817. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80818. })(BABYLON || (BABYLON = {}));
  80819. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80820. "use strict";
  80821. var BABYLON;
  80822. (function (BABYLON) {
  80823. var MorphTarget = /** @class */ (function () {
  80824. function MorphTarget(name, influence) {
  80825. if (influence === void 0) { influence = 0; }
  80826. this.name = name;
  80827. this.animations = new Array();
  80828. this._positions = null;
  80829. this._normals = null;
  80830. this._tangents = null;
  80831. this.onInfluenceChanged = new BABYLON.Observable();
  80832. this.influence = influence;
  80833. }
  80834. Object.defineProperty(MorphTarget.prototype, "influence", {
  80835. get: function () {
  80836. return this._influence;
  80837. },
  80838. set: function (influence) {
  80839. if (this._influence === influence) {
  80840. return;
  80841. }
  80842. var previous = this._influence;
  80843. this._influence = influence;
  80844. if (this.onInfluenceChanged.hasObservers) {
  80845. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80846. }
  80847. },
  80848. enumerable: true,
  80849. configurable: true
  80850. });
  80851. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80852. get: function () {
  80853. return !!this._positions;
  80854. },
  80855. enumerable: true,
  80856. configurable: true
  80857. });
  80858. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80859. get: function () {
  80860. return !!this._normals;
  80861. },
  80862. enumerable: true,
  80863. configurable: true
  80864. });
  80865. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80866. get: function () {
  80867. return !!this._tangents;
  80868. },
  80869. enumerable: true,
  80870. configurable: true
  80871. });
  80872. MorphTarget.prototype.setPositions = function (data) {
  80873. this._positions = data;
  80874. };
  80875. MorphTarget.prototype.getPositions = function () {
  80876. return this._positions;
  80877. };
  80878. MorphTarget.prototype.setNormals = function (data) {
  80879. this._normals = data;
  80880. };
  80881. MorphTarget.prototype.getNormals = function () {
  80882. return this._normals;
  80883. };
  80884. MorphTarget.prototype.setTangents = function (data) {
  80885. this._tangents = data;
  80886. };
  80887. MorphTarget.prototype.getTangents = function () {
  80888. return this._tangents;
  80889. };
  80890. /**
  80891. * Serializes the current target into a Serialization object.
  80892. * Returns the serialized object.
  80893. */
  80894. MorphTarget.prototype.serialize = function () {
  80895. var serializationObject = {};
  80896. serializationObject.name = this.name;
  80897. serializationObject.influence = this.influence;
  80898. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80899. if (this.hasNormals) {
  80900. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80901. }
  80902. if (this.hasTangents) {
  80903. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80904. }
  80905. // Animations
  80906. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80907. return serializationObject;
  80908. };
  80909. // Statics
  80910. MorphTarget.Parse = function (serializationObject) {
  80911. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80912. result.setPositions(serializationObject.positions);
  80913. if (serializationObject.normals) {
  80914. result.setNormals(serializationObject.normals);
  80915. }
  80916. if (serializationObject.tangents) {
  80917. result.setTangents(serializationObject.tangents);
  80918. }
  80919. // Animations
  80920. if (serializationObject.animations) {
  80921. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80922. var parsedAnimation = serializationObject.animations[animationIndex];
  80923. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80924. }
  80925. }
  80926. return result;
  80927. };
  80928. MorphTarget.FromMesh = function (mesh, name, influence) {
  80929. if (!name) {
  80930. name = mesh.name;
  80931. }
  80932. var result = new MorphTarget(name, influence);
  80933. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80934. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80935. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80936. }
  80937. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80938. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80939. }
  80940. return result;
  80941. };
  80942. return MorphTarget;
  80943. }());
  80944. BABYLON.MorphTarget = MorphTarget;
  80945. })(BABYLON || (BABYLON = {}));
  80946. //# sourceMappingURL=babylon.morphTarget.js.map
  80947. "use strict";
  80948. var BABYLON;
  80949. (function (BABYLON) {
  80950. var MorphTargetManager = /** @class */ (function () {
  80951. function MorphTargetManager(scene) {
  80952. if (scene === void 0) { scene = null; }
  80953. this._targets = new Array();
  80954. this._targetObservable = new Array();
  80955. this._activeTargets = new BABYLON.SmartArray(16);
  80956. this._supportsNormals = false;
  80957. this._supportsTangents = false;
  80958. this._vertexCount = 0;
  80959. this._uniqueId = 0;
  80960. this._tempInfluences = new Array();
  80961. if (!scene) {
  80962. scene = BABYLON.Engine.LastCreatedScene;
  80963. }
  80964. this._scene = scene;
  80965. if (this._scene) {
  80966. this._scene.morphTargetManagers.push(this);
  80967. this._uniqueId = this._scene.getUniqueId();
  80968. }
  80969. }
  80970. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80971. get: function () {
  80972. return this._uniqueId;
  80973. },
  80974. enumerable: true,
  80975. configurable: true
  80976. });
  80977. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80978. get: function () {
  80979. return this._vertexCount;
  80980. },
  80981. enumerable: true,
  80982. configurable: true
  80983. });
  80984. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80985. get: function () {
  80986. return this._supportsNormals;
  80987. },
  80988. enumerable: true,
  80989. configurable: true
  80990. });
  80991. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80992. get: function () {
  80993. return this._supportsTangents;
  80994. },
  80995. enumerable: true,
  80996. configurable: true
  80997. });
  80998. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80999. get: function () {
  81000. return this._targets.length;
  81001. },
  81002. enumerable: true,
  81003. configurable: true
  81004. });
  81005. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  81006. get: function () {
  81007. return this._activeTargets.length;
  81008. },
  81009. enumerable: true,
  81010. configurable: true
  81011. });
  81012. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  81013. get: function () {
  81014. return this._influences;
  81015. },
  81016. enumerable: true,
  81017. configurable: true
  81018. });
  81019. MorphTargetManager.prototype.getActiveTarget = function (index) {
  81020. return this._activeTargets.data[index];
  81021. };
  81022. MorphTargetManager.prototype.getTarget = function (index) {
  81023. return this._targets[index];
  81024. };
  81025. MorphTargetManager.prototype.addTarget = function (target) {
  81026. var _this = this;
  81027. this._targets.push(target);
  81028. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  81029. _this._syncActiveTargets(needUpdate);
  81030. }));
  81031. this._syncActiveTargets(true);
  81032. };
  81033. MorphTargetManager.prototype.removeTarget = function (target) {
  81034. var index = this._targets.indexOf(target);
  81035. if (index >= 0) {
  81036. this._targets.splice(index, 1);
  81037. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81038. this._syncActiveTargets(true);
  81039. }
  81040. };
  81041. /**
  81042. * Serializes the current manager into a Serialization object.
  81043. * Returns the serialized object.
  81044. */
  81045. MorphTargetManager.prototype.serialize = function () {
  81046. var serializationObject = {};
  81047. serializationObject.id = this.uniqueId;
  81048. serializationObject.targets = [];
  81049. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81050. var target = _a[_i];
  81051. serializationObject.targets.push(target.serialize());
  81052. }
  81053. return serializationObject;
  81054. };
  81055. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81056. var influenceCount = 0;
  81057. this._activeTargets.reset();
  81058. this._supportsNormals = true;
  81059. this._supportsTangents = true;
  81060. this._vertexCount = 0;
  81061. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81062. var target = _a[_i];
  81063. this._activeTargets.push(target);
  81064. this._tempInfluences[influenceCount++] = target.influence;
  81065. var positions = target.getPositions();
  81066. if (positions) {
  81067. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81068. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81069. var vertexCount = positions.length / 3;
  81070. if (this._vertexCount === 0) {
  81071. this._vertexCount = vertexCount;
  81072. }
  81073. else if (this._vertexCount !== vertexCount) {
  81074. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81075. return;
  81076. }
  81077. }
  81078. }
  81079. if (!this._influences || this._influences.length !== influenceCount) {
  81080. this._influences = new Float32Array(influenceCount);
  81081. }
  81082. for (var index = 0; index < influenceCount; index++) {
  81083. this._influences[index] = this._tempInfluences[index];
  81084. }
  81085. if (needUpdate && this._scene) {
  81086. // Flag meshes as dirty to resync with the active targets
  81087. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81088. var mesh = _c[_b];
  81089. if (mesh.morphTargetManager === this) {
  81090. mesh._syncGeometryWithMorphTargetManager();
  81091. }
  81092. }
  81093. }
  81094. };
  81095. // Statics
  81096. MorphTargetManager.Parse = function (serializationObject, scene) {
  81097. var result = new MorphTargetManager(scene);
  81098. result._uniqueId = serializationObject.id;
  81099. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81100. var targetData = _a[_i];
  81101. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81102. }
  81103. return result;
  81104. };
  81105. return MorphTargetManager;
  81106. }());
  81107. BABYLON.MorphTargetManager = MorphTargetManager;
  81108. })(BABYLON || (BABYLON = {}));
  81109. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81110. "use strict";
  81111. var BABYLON;
  81112. (function (BABYLON) {
  81113. var Octree = /** @class */ (function () {
  81114. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81115. if (maxDepth === void 0) { maxDepth = 2; }
  81116. this.maxDepth = maxDepth;
  81117. this.dynamicContent = new Array();
  81118. this._maxBlockCapacity = maxBlockCapacity || 64;
  81119. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81120. this._creationFunc = creationFunc;
  81121. }
  81122. // Methods
  81123. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81124. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81125. };
  81126. Octree.prototype.addMesh = function (entry) {
  81127. for (var index = 0; index < this.blocks.length; index++) {
  81128. var block = this.blocks[index];
  81129. block.addEntry(entry);
  81130. }
  81131. };
  81132. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81133. this._selectionContent.reset();
  81134. for (var index = 0; index < this.blocks.length; index++) {
  81135. var block = this.blocks[index];
  81136. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81137. }
  81138. if (allowDuplicate) {
  81139. this._selectionContent.concat(this.dynamicContent);
  81140. }
  81141. else {
  81142. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81143. }
  81144. return this._selectionContent;
  81145. };
  81146. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81147. this._selectionContent.reset();
  81148. for (var index = 0; index < this.blocks.length; index++) {
  81149. var block = this.blocks[index];
  81150. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81151. }
  81152. if (allowDuplicate) {
  81153. this._selectionContent.concat(this.dynamicContent);
  81154. }
  81155. else {
  81156. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81157. }
  81158. return this._selectionContent;
  81159. };
  81160. Octree.prototype.intersectsRay = function (ray) {
  81161. this._selectionContent.reset();
  81162. for (var index = 0; index < this.blocks.length; index++) {
  81163. var block = this.blocks[index];
  81164. block.intersectsRay(ray, this._selectionContent);
  81165. }
  81166. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81167. return this._selectionContent;
  81168. };
  81169. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81170. target.blocks = new Array();
  81171. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81172. // Segmenting space
  81173. for (var x = 0; x < 2; x++) {
  81174. for (var y = 0; y < 2; y++) {
  81175. for (var z = 0; z < 2; z++) {
  81176. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81177. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81178. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81179. block.addEntries(entries);
  81180. target.blocks.push(block);
  81181. }
  81182. }
  81183. }
  81184. };
  81185. Octree.CreationFuncForMeshes = function (entry, block) {
  81186. var boundingInfo = entry.getBoundingInfo();
  81187. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81188. block.entries.push(entry);
  81189. }
  81190. };
  81191. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81192. var boundingInfo = entry.getBoundingInfo();
  81193. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81194. block.entries.push(entry);
  81195. }
  81196. };
  81197. return Octree;
  81198. }());
  81199. BABYLON.Octree = Octree;
  81200. })(BABYLON || (BABYLON = {}));
  81201. //# sourceMappingURL=babylon.octree.js.map
  81202. "use strict";
  81203. var BABYLON;
  81204. (function (BABYLON) {
  81205. var OctreeBlock = /** @class */ (function () {
  81206. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81207. this.entries = new Array();
  81208. this._boundingVectors = new Array();
  81209. this._capacity = capacity;
  81210. this._depth = depth;
  81211. this._maxDepth = maxDepth;
  81212. this._creationFunc = creationFunc;
  81213. this._minPoint = minPoint;
  81214. this._maxPoint = maxPoint;
  81215. this._boundingVectors.push(minPoint.clone());
  81216. this._boundingVectors.push(maxPoint.clone());
  81217. this._boundingVectors.push(minPoint.clone());
  81218. this._boundingVectors[2].x = maxPoint.x;
  81219. this._boundingVectors.push(minPoint.clone());
  81220. this._boundingVectors[3].y = maxPoint.y;
  81221. this._boundingVectors.push(minPoint.clone());
  81222. this._boundingVectors[4].z = maxPoint.z;
  81223. this._boundingVectors.push(maxPoint.clone());
  81224. this._boundingVectors[5].z = minPoint.z;
  81225. this._boundingVectors.push(maxPoint.clone());
  81226. this._boundingVectors[6].x = minPoint.x;
  81227. this._boundingVectors.push(maxPoint.clone());
  81228. this._boundingVectors[7].y = minPoint.y;
  81229. }
  81230. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81231. // Property
  81232. get: function () {
  81233. return this._capacity;
  81234. },
  81235. enumerable: true,
  81236. configurable: true
  81237. });
  81238. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81239. get: function () {
  81240. return this._minPoint;
  81241. },
  81242. enumerable: true,
  81243. configurable: true
  81244. });
  81245. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81246. get: function () {
  81247. return this._maxPoint;
  81248. },
  81249. enumerable: true,
  81250. configurable: true
  81251. });
  81252. // Methods
  81253. OctreeBlock.prototype.addEntry = function (entry) {
  81254. if (this.blocks) {
  81255. for (var index = 0; index < this.blocks.length; index++) {
  81256. var block = this.blocks[index];
  81257. block.addEntry(entry);
  81258. }
  81259. return;
  81260. }
  81261. this._creationFunc(entry, this);
  81262. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81263. this.createInnerBlocks();
  81264. }
  81265. };
  81266. OctreeBlock.prototype.addEntries = function (entries) {
  81267. for (var index = 0; index < entries.length; index++) {
  81268. var mesh = entries[index];
  81269. this.addEntry(mesh);
  81270. }
  81271. };
  81272. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81273. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81274. if (this.blocks) {
  81275. for (var index = 0; index < this.blocks.length; index++) {
  81276. var block = this.blocks[index];
  81277. block.select(frustumPlanes, selection, allowDuplicate);
  81278. }
  81279. return;
  81280. }
  81281. if (allowDuplicate) {
  81282. selection.concat(this.entries);
  81283. }
  81284. else {
  81285. selection.concatWithNoDuplicate(this.entries);
  81286. }
  81287. }
  81288. };
  81289. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81290. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81291. if (this.blocks) {
  81292. for (var index = 0; index < this.blocks.length; index++) {
  81293. var block = this.blocks[index];
  81294. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81295. }
  81296. return;
  81297. }
  81298. if (allowDuplicate) {
  81299. selection.concat(this.entries);
  81300. }
  81301. else {
  81302. selection.concatWithNoDuplicate(this.entries);
  81303. }
  81304. }
  81305. };
  81306. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81307. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81308. if (this.blocks) {
  81309. for (var index = 0; index < this.blocks.length; index++) {
  81310. var block = this.blocks[index];
  81311. block.intersectsRay(ray, selection);
  81312. }
  81313. return;
  81314. }
  81315. selection.concatWithNoDuplicate(this.entries);
  81316. }
  81317. };
  81318. OctreeBlock.prototype.createInnerBlocks = function () {
  81319. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81320. };
  81321. return OctreeBlock;
  81322. }());
  81323. BABYLON.OctreeBlock = OctreeBlock;
  81324. })(BABYLON || (BABYLON = {}));
  81325. //# sourceMappingURL=babylon.octreeBlock.js.map
  81326. "use strict";
  81327. var BABYLON;
  81328. (function (BABYLON) {
  81329. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81330. __extends(VRDistortionCorrectionPostProcess, _super);
  81331. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81332. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81333. 'LensCenter',
  81334. 'Scale',
  81335. 'ScaleIn',
  81336. 'HmdWarpParam'
  81337. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81338. _this._isRightEye = isRightEye;
  81339. _this._distortionFactors = vrMetrics.distortionK;
  81340. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81341. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81342. _this.adaptScaleToCurrentViewport = true;
  81343. _this.onSizeChangedObservable.add(function () {
  81344. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81345. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81346. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81347. });
  81348. _this.onApplyObservable.add(function (effect) {
  81349. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81350. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81351. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81352. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81353. });
  81354. return _this;
  81355. }
  81356. return VRDistortionCorrectionPostProcess;
  81357. }(BABYLON.PostProcess));
  81358. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81359. })(BABYLON || (BABYLON = {}));
  81360. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81361. "use strict";
  81362. var BABYLON;
  81363. (function (BABYLON) {
  81364. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81365. __extends(AnaglyphPostProcess, _super);
  81366. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81367. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81368. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81369. _this.onApplyObservable.add(function (effect) {
  81370. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81371. });
  81372. return _this;
  81373. }
  81374. return AnaglyphPostProcess;
  81375. }(BABYLON.PostProcess));
  81376. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81377. })(BABYLON || (BABYLON = {}));
  81378. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81379. "use strict";
  81380. var BABYLON;
  81381. (function (BABYLON) {
  81382. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81383. __extends(StereoscopicInterlacePostProcess, _super);
  81384. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81385. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81386. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81387. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81388. _this.onSizeChangedObservable.add(function () {
  81389. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81390. });
  81391. _this.onApplyObservable.add(function (effect) {
  81392. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81393. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81394. });
  81395. return _this;
  81396. }
  81397. return StereoscopicInterlacePostProcess;
  81398. }(BABYLON.PostProcess));
  81399. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81400. })(BABYLON || (BABYLON = {}));
  81401. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81402. "use strict";
  81403. var BABYLON;
  81404. (function (BABYLON) {
  81405. /**
  81406. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81407. * Screen rotation is taken into account.
  81408. */
  81409. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81410. function FreeCameraDeviceOrientationInput() {
  81411. var _this = this;
  81412. this._screenOrientationAngle = 0;
  81413. this._screenQuaternion = new BABYLON.Quaternion();
  81414. this._alpha = 0;
  81415. this._beta = 0;
  81416. this._gamma = 0;
  81417. this._orientationChanged = function () {
  81418. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81419. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81420. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81421. };
  81422. this._deviceOrientation = function (evt) {
  81423. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81424. _this._beta = evt.beta !== null ? evt.beta : 0;
  81425. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81426. };
  81427. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81428. this._orientationChanged();
  81429. }
  81430. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81431. get: function () {
  81432. return this._camera;
  81433. },
  81434. set: function (camera) {
  81435. this._camera = camera;
  81436. if (this._camera != null && !this._camera.rotationQuaternion) {
  81437. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81438. }
  81439. },
  81440. enumerable: true,
  81441. configurable: true
  81442. });
  81443. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81444. window.addEventListener("orientationchange", this._orientationChanged);
  81445. window.addEventListener("deviceorientation", this._deviceOrientation);
  81446. //In certain cases, the attach control is called AFTER orientation was changed,
  81447. //So this is needed.
  81448. this._orientationChanged();
  81449. };
  81450. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81451. window.removeEventListener("orientationchange", this._orientationChanged);
  81452. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81453. };
  81454. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81455. //if no device orientation provided, don't update the rotation.
  81456. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81457. if (!this._alpha)
  81458. return;
  81459. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81460. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81461. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81462. //Mirror on XY Plane
  81463. this._camera.rotationQuaternion.z *= -1;
  81464. this._camera.rotationQuaternion.w *= -1;
  81465. };
  81466. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81467. return "FreeCameraDeviceOrientationInput";
  81468. };
  81469. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81470. return "deviceOrientation";
  81471. };
  81472. return FreeCameraDeviceOrientationInput;
  81473. }());
  81474. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81475. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81476. })(BABYLON || (BABYLON = {}));
  81477. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81478. "use strict";
  81479. var BABYLON;
  81480. (function (BABYLON) {
  81481. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81482. function ArcRotateCameraVRDeviceOrientationInput() {
  81483. this.alphaCorrection = 1;
  81484. this.betaCorrection = 1;
  81485. this.gammaCorrection = 1;
  81486. this._alpha = 0;
  81487. this._gamma = 0;
  81488. this._dirty = false;
  81489. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81490. }
  81491. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81492. this.camera.attachControl(element, noPreventDefault);
  81493. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81494. };
  81495. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81496. if (evt.alpha !== null) {
  81497. this._alpha = +evt.alpha | 0;
  81498. }
  81499. if (evt.gamma !== null) {
  81500. this._gamma = +evt.gamma | 0;
  81501. }
  81502. this._dirty = true;
  81503. };
  81504. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81505. if (this._dirty) {
  81506. this._dirty = false;
  81507. if (this._gamma < 0) {
  81508. this._gamma = 180 + this._gamma;
  81509. }
  81510. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81511. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81512. }
  81513. };
  81514. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81515. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81516. };
  81517. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81518. return "ArcRotateCameraVRDeviceOrientationInput";
  81519. };
  81520. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81521. return "VRDeviceOrientation";
  81522. };
  81523. return ArcRotateCameraVRDeviceOrientationInput;
  81524. }());
  81525. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81526. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81527. })(BABYLON || (BABYLON = {}));
  81528. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81529. "use strict";
  81530. var BABYLON;
  81531. (function (BABYLON) {
  81532. var VRCameraMetrics = /** @class */ (function () {
  81533. function VRCameraMetrics() {
  81534. this.compensateDistortion = true;
  81535. }
  81536. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81537. get: function () {
  81538. return this.hResolution / (2 * this.vResolution);
  81539. },
  81540. enumerable: true,
  81541. configurable: true
  81542. });
  81543. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81544. get: function () {
  81545. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81546. },
  81547. enumerable: true,
  81548. configurable: true
  81549. });
  81550. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81551. get: function () {
  81552. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81553. var h = (4 * meters) / this.hScreenSize;
  81554. return BABYLON.Matrix.Translation(h, 0, 0);
  81555. },
  81556. enumerable: true,
  81557. configurable: true
  81558. });
  81559. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81560. get: function () {
  81561. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81562. var h = (4 * meters) / this.hScreenSize;
  81563. return BABYLON.Matrix.Translation(-h, 0, 0);
  81564. },
  81565. enumerable: true,
  81566. configurable: true
  81567. });
  81568. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81569. get: function () {
  81570. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81571. },
  81572. enumerable: true,
  81573. configurable: true
  81574. });
  81575. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81576. get: function () {
  81577. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81578. },
  81579. enumerable: true,
  81580. configurable: true
  81581. });
  81582. VRCameraMetrics.GetDefault = function () {
  81583. var result = new VRCameraMetrics();
  81584. result.hResolution = 1280;
  81585. result.vResolution = 800;
  81586. result.hScreenSize = 0.149759993;
  81587. result.vScreenSize = 0.0935999975;
  81588. result.vScreenCenter = 0.0467999987;
  81589. result.eyeToScreenDistance = 0.0410000011;
  81590. result.lensSeparationDistance = 0.0635000020;
  81591. result.interpupillaryDistance = 0.0640000030;
  81592. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81593. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81594. result.postProcessScaleFactor = 1.714605507808412;
  81595. result.lensCenterOffset = 0.151976421;
  81596. return result;
  81597. };
  81598. return VRCameraMetrics;
  81599. }());
  81600. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81601. })(BABYLON || (BABYLON = {}));
  81602. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81603. "use strict";
  81604. var BABYLON;
  81605. (function (BABYLON) {
  81606. /**
  81607. * This represents a WebVR camera.
  81608. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81609. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81610. */
  81611. var WebVRFreeCamera = /** @class */ (function (_super) {
  81612. __extends(WebVRFreeCamera, _super);
  81613. /**
  81614. * Instantiates a WebVRFreeCamera.
  81615. * @param name The name of the WebVRFreeCamera
  81616. * @param position The starting anchor position for the camera
  81617. * @param scene The scene the camera belongs to
  81618. * @param webVROptions a set of customizable options for the webVRCamera
  81619. */
  81620. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81621. if (webVROptions === void 0) { webVROptions = {}; }
  81622. var _this = _super.call(this, name, position, scene) || this;
  81623. _this.webVROptions = webVROptions;
  81624. /**
  81625. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81626. */
  81627. _this._vrDevice = null;
  81628. /**
  81629. * The rawPose of the vrDevice.
  81630. */
  81631. _this.rawPose = null;
  81632. _this._specsVersion = "1.1";
  81633. _this._attached = false;
  81634. _this._descendants = [];
  81635. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81636. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81637. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81638. _this._standingMatrix = null;
  81639. /**
  81640. * Represents device position in babylon space.
  81641. */
  81642. _this.devicePosition = BABYLON.Vector3.Zero();
  81643. /**
  81644. * Represents device rotation in babylon space.
  81645. */
  81646. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81647. /**
  81648. * The scale of the device to be used when translating from device space to babylon space.
  81649. */
  81650. _this.deviceScaleFactor = 1;
  81651. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81652. _this._worldToDevice = BABYLON.Matrix.Identity();
  81653. /**
  81654. * References to the webVR controllers for the vrDevice.
  81655. */
  81656. _this.controllers = [];
  81657. /**
  81658. * Emits an event when a controller is attached.
  81659. */
  81660. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81661. /**
  81662. * Emits an event when a controller's mesh has been loaded;
  81663. */
  81664. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81665. /**
  81666. * If the rig cameras be used as parent instead of this camera.
  81667. */
  81668. _this.rigParenting = true;
  81669. _this._defaultHeight = undefined;
  81670. _this._workingVector = BABYLON.Vector3.Zero();
  81671. _this._oneVector = BABYLON.Vector3.One();
  81672. _this._workingMatrix = BABYLON.Matrix.Identity();
  81673. _this._cache.position = BABYLON.Vector3.Zero();
  81674. if (webVROptions.defaultHeight) {
  81675. _this._defaultHeight = webVROptions.defaultHeight;
  81676. _this.position.y = _this._defaultHeight;
  81677. }
  81678. _this.minZ = 0.1;
  81679. //legacy support - the compensation boolean was removed.
  81680. if (arguments.length === 5) {
  81681. _this.webVROptions = arguments[4];
  81682. }
  81683. // default webVR options
  81684. if (_this.webVROptions.trackPosition == undefined) {
  81685. _this.webVROptions.trackPosition = true;
  81686. }
  81687. if (_this.webVROptions.controllerMeshes == undefined) {
  81688. _this.webVROptions.controllerMeshes = true;
  81689. }
  81690. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81691. _this.webVROptions.defaultLightingOnControllers = true;
  81692. }
  81693. _this.rotationQuaternion = new BABYLON.Quaternion();
  81694. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81695. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81696. }
  81697. //enable VR
  81698. var engine = _this.getEngine();
  81699. _this._onVREnabled = function (success) { if (success) {
  81700. _this.initControllers();
  81701. } };
  81702. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  81703. engine.initWebVR().add(function (event) {
  81704. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  81705. return;
  81706. }
  81707. _this._vrDevice = event.vrDisplay;
  81708. //reset the rig parameters.
  81709. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81710. if (_this._attached) {
  81711. _this.getEngine().enableVR();
  81712. }
  81713. });
  81714. if (typeof (VRFrameData) !== "undefined")
  81715. _this._frameData = new VRFrameData();
  81716. /**
  81717. * The idea behind the following lines:
  81718. * objects that have the camera as parent should actually have the rig cameras as a parent.
  81719. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  81720. * the second will not show it correctly.
  81721. *
  81722. * To solve this - each object that has the camera as parent will be added to a protected array.
  81723. * When the rig camera renders, it will take this array and set all of those to be its children.
  81724. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  81725. * Amazing!
  81726. */
  81727. scene.onBeforeCameraRenderObservable.add(function (camera) {
  81728. if (camera.parent === _this && _this.rigParenting) {
  81729. _this._descendants = _this.getDescendants(true, function (n) {
  81730. // don't take the cameras or the controllers!
  81731. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  81732. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  81733. return !isController && !isRigCamera;
  81734. });
  81735. _this._descendants.forEach(function (node) {
  81736. node.parent = camera;
  81737. });
  81738. }
  81739. });
  81740. scene.onAfterCameraRenderObservable.add(function (camera) {
  81741. if (camera.parent === _this && _this.rigParenting) {
  81742. _this._descendants.forEach(function (node) {
  81743. node.parent = _this;
  81744. });
  81745. }
  81746. });
  81747. return _this;
  81748. }
  81749. /**
  81750. * Gets the device distance from the ground in meters.
  81751. * @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.
  81752. */
  81753. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  81754. if (this._standingMatrix) {
  81755. // Add standing matrix offset to get real offset from ground in room
  81756. this._standingMatrix.getTranslationToRef(this._workingVector);
  81757. return this._deviceRoomPosition.y + this._workingVector.y;
  81758. }
  81759. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  81760. return this._defaultHeight || 0;
  81761. };
  81762. /**
  81763. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81764. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  81765. */
  81766. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  81767. var _this = this;
  81768. if (callback === void 0) { callback = function (bool) { }; }
  81769. // Use standing matrix if available
  81770. this.getEngine().initWebVRAsync().then(function (result) {
  81771. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  81772. callback(false);
  81773. }
  81774. else {
  81775. _this._standingMatrix = new BABYLON.Matrix();
  81776. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  81777. if (!_this.getScene().useRightHandedSystem) {
  81778. [2, 6, 8, 9, 14].forEach(function (num) {
  81779. if (_this._standingMatrix) {
  81780. _this._standingMatrix.m[num] *= -1;
  81781. }
  81782. });
  81783. }
  81784. callback(true);
  81785. }
  81786. });
  81787. };
  81788. /**
  81789. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81790. * @returns A promise with a boolean set to if the standing matrix is supported.
  81791. */
  81792. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81793. var _this = this;
  81794. return new Promise(function (res, rej) {
  81795. _this.useStandingMatrix(function (supported) {
  81796. res(supported);
  81797. });
  81798. });
  81799. };
  81800. /**
  81801. * Disposes the camera
  81802. */
  81803. WebVRFreeCamera.prototype.dispose = function () {
  81804. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81805. _super.prototype.dispose.call(this);
  81806. };
  81807. /**
  81808. * Gets a vrController by name.
  81809. * @param name The name of the controller to retreive
  81810. * @returns the controller matching the name specified or null if not found
  81811. */
  81812. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81813. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81814. var gp = _a[_i];
  81815. if (gp.hand === name) {
  81816. return gp;
  81817. }
  81818. }
  81819. return null;
  81820. };
  81821. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81822. /**
  81823. * The controller corrisponding to the users left hand.
  81824. */
  81825. get: function () {
  81826. if (!this._leftController) {
  81827. this._leftController = this.getControllerByName("left");
  81828. }
  81829. return this._leftController;
  81830. },
  81831. enumerable: true,
  81832. configurable: true
  81833. });
  81834. ;
  81835. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81836. /**
  81837. * The controller corrisponding to the users right hand.
  81838. */
  81839. get: function () {
  81840. if (!this._rightController) {
  81841. this._rightController = this.getControllerByName("right");
  81842. }
  81843. return this._rightController;
  81844. },
  81845. enumerable: true,
  81846. configurable: true
  81847. });
  81848. ;
  81849. /**
  81850. * Casts a ray forward from the vrCamera's gaze.
  81851. * @param length Length of the ray (default: 100)
  81852. * @returns the ray corrisponding to the gaze
  81853. */
  81854. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81855. if (length === void 0) { length = 100; }
  81856. if (this.leftCamera) {
  81857. // Use left eye to avoid computation to compute center on every call
  81858. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81859. }
  81860. else {
  81861. return _super.prototype.getForwardRay.call(this, length);
  81862. }
  81863. };
  81864. /**
  81865. * Updates the camera based on device's frame data
  81866. */
  81867. WebVRFreeCamera.prototype._checkInputs = function () {
  81868. if (this._vrDevice && this._vrDevice.isPresenting) {
  81869. this._vrDevice.getFrameData(this._frameData);
  81870. this.updateFromDevice(this._frameData.pose);
  81871. }
  81872. _super.prototype._checkInputs.call(this);
  81873. };
  81874. /**
  81875. * Updates the poseControlled values based on the input device pose.
  81876. * @param poseData Pose coming from the device
  81877. */
  81878. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81879. if (poseData && poseData.orientation) {
  81880. this.rawPose = poseData;
  81881. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81882. if (this.getScene().useRightHandedSystem) {
  81883. this._deviceRoomRotationQuaternion.z *= -1;
  81884. this._deviceRoomRotationQuaternion.w *= -1;
  81885. }
  81886. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81887. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81888. if (this.getScene().useRightHandedSystem) {
  81889. this._deviceRoomPosition.z *= -1;
  81890. }
  81891. }
  81892. }
  81893. };
  81894. /**
  81895. * WebVR's attach control will start broadcasting frames to the device.
  81896. * Note that in certain browsers (chrome for example) this function must be called
  81897. * within a user-interaction callback. Example:
  81898. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81899. *
  81900. * @param element html element to attach the vrDevice to
  81901. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81902. */
  81903. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81904. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81905. this._attached = true;
  81906. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81907. if (this._vrDevice) {
  81908. this.getEngine().enableVR();
  81909. }
  81910. };
  81911. /**
  81912. * Detaches the camera from the html element and disables VR
  81913. *
  81914. * @param element html element to detach from
  81915. */
  81916. WebVRFreeCamera.prototype.detachControl = function (element) {
  81917. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81918. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81919. _super.prototype.detachControl.call(this, element);
  81920. this._attached = false;
  81921. this.getEngine().disableVR();
  81922. };
  81923. /**
  81924. * @returns the name of this class
  81925. */
  81926. WebVRFreeCamera.prototype.getClassName = function () {
  81927. return "WebVRFreeCamera";
  81928. };
  81929. /**
  81930. * Calls resetPose on the vrDisplay
  81931. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81932. */
  81933. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81934. //uses the vrDisplay's "resetPose()".
  81935. //pitch and roll won't be affected.
  81936. this._vrDevice.resetPose();
  81937. };
  81938. /**
  81939. * Updates the rig cameras (left and right eye)
  81940. */
  81941. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81942. var camLeft = this._rigCameras[0];
  81943. var camRight = this._rigCameras[1];
  81944. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81945. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81946. camLeft.position.copyFrom(this._deviceRoomPosition);
  81947. camRight.position.copyFrom(this._deviceRoomPosition);
  81948. };
  81949. /**
  81950. * Updates the cached values of the camera
  81951. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81952. */
  81953. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81954. var _this = this;
  81955. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81956. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81957. if (!this.updateCacheCalled) {
  81958. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81959. this.updateCacheCalled = true;
  81960. this.update();
  81961. }
  81962. // Set working vector to the device position in room space rotated by the new rotation
  81963. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81964. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81965. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81966. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81967. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81968. // Add translation from anchor position
  81969. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81970. this._workingVector.addInPlace(this.position);
  81971. this._workingVector.subtractInPlace(this._cache.position);
  81972. this._deviceToWorld.setTranslation(this._workingVector);
  81973. // Set an inverted matrix to be used when updating the camera
  81974. this._deviceToWorld.invertToRef(this._worldToDevice);
  81975. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81976. this.controllers.forEach(function (controller) {
  81977. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81978. controller.update();
  81979. });
  81980. }
  81981. if (!ignoreParentClass) {
  81982. _super.prototype._updateCache.call(this);
  81983. }
  81984. this.updateCacheCalled = false;
  81985. };
  81986. /**
  81987. * Updates the current device position and rotation in the babylon world
  81988. */
  81989. WebVRFreeCamera.prototype.update = function () {
  81990. // Get current device position in babylon world
  81991. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81992. // Get current device rotation in babylon world
  81993. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81994. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81995. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81996. _super.prototype.update.call(this);
  81997. };
  81998. /**
  81999. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  82000. * @returns an identity matrix
  82001. */
  82002. WebVRFreeCamera.prototype._getViewMatrix = function () {
  82003. return BABYLON.Matrix.Identity();
  82004. };
  82005. /**
  82006. * This function is called by the two RIG cameras.
  82007. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  82008. */
  82009. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  82010. var _this = this;
  82011. // Update the parent camera prior to using a child camera to avoid desynchronization
  82012. var parentCamera = this._cameraRigParams["parentCamera"];
  82013. parentCamera._updateCache();
  82014. //WebVR 1.1
  82015. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  82016. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  82017. if (!this.getScene().useRightHandedSystem) {
  82018. [2, 6, 8, 9, 14].forEach(function (num) {
  82019. _this._webvrViewMatrix.m[num] *= -1;
  82020. });
  82021. }
  82022. // update the camera rotation matrix
  82023. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  82024. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  82025. // Computing target and final matrix
  82026. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  82027. // should the view matrix be updated with scale and position offset?
  82028. if (parentCamera.deviceScaleFactor !== 1) {
  82029. this._webvrViewMatrix.invert();
  82030. // scale the position, if set
  82031. if (parentCamera.deviceScaleFactor) {
  82032. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  82033. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  82034. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  82035. }
  82036. this._webvrViewMatrix.invert();
  82037. }
  82038. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82039. return this._webvrViewMatrix;
  82040. };
  82041. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82042. var _this = this;
  82043. var parentCamera = this.parent;
  82044. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82045. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82046. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82047. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82048. //babylon compatible matrix
  82049. if (!this.getScene().useRightHandedSystem) {
  82050. [8, 9, 10, 11].forEach(function (num) {
  82051. _this._projectionMatrix.m[num] *= -1;
  82052. });
  82053. }
  82054. return this._projectionMatrix;
  82055. };
  82056. /**
  82057. * Initializes the controllers and their meshes
  82058. */
  82059. WebVRFreeCamera.prototype.initControllers = function () {
  82060. var _this = this;
  82061. this.controllers = [];
  82062. var manager = this.getScene().gamepadManager;
  82063. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82064. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82065. var webVrController = gamepad;
  82066. if (webVrController.defaultModel) {
  82067. webVrController.defaultModel.setEnabled(false);
  82068. }
  82069. if (webVrController.hand === "right") {
  82070. _this._rightController = null;
  82071. }
  82072. if (webVrController.hand === "left") {
  82073. _this._leftController = null;
  82074. }
  82075. var controllerIndex = _this.controllers.indexOf(webVrController);
  82076. if (controllerIndex !== -1) {
  82077. _this.controllers.splice(controllerIndex, 1);
  82078. }
  82079. }
  82080. });
  82081. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82082. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82083. var webVrController_1 = gamepad;
  82084. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82085. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82086. if (_this.webVROptions.controllerMeshes) {
  82087. if (webVrController_1.defaultModel) {
  82088. webVrController_1.defaultModel.setEnabled(true);
  82089. }
  82090. else {
  82091. // Load the meshes
  82092. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82093. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82094. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82095. if (_this.webVROptions.defaultLightingOnControllers) {
  82096. if (!_this._lightOnControllers) {
  82097. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82098. }
  82099. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82100. var children = mesh.getChildren();
  82101. if (children.length !== 0) {
  82102. children.forEach(function (mesh) {
  82103. light.includedOnlyMeshes.push(mesh);
  82104. activateLightOnSubMeshes_1(mesh, light);
  82105. });
  82106. }
  82107. };
  82108. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82109. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82110. }
  82111. });
  82112. }
  82113. }
  82114. webVrController_1.attachToPoseControlledCamera(_this);
  82115. // since this is async - sanity check. Is the controller already stored?
  82116. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82117. //add to the controllers array
  82118. _this.controllers.push(webVrController_1);
  82119. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82120. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82121. // So we're overriding setting left & right manually to be sure
  82122. var firstViveWandDetected = false;
  82123. for (var i = 0; i < _this.controllers.length; i++) {
  82124. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82125. if (!firstViveWandDetected) {
  82126. firstViveWandDetected = true;
  82127. _this.controllers[i].hand = "left";
  82128. }
  82129. else {
  82130. _this.controllers[i].hand = "right";
  82131. }
  82132. }
  82133. }
  82134. //did we find enough controllers? Great! let the developer know.
  82135. if (_this.controllers.length >= 2) {
  82136. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82137. }
  82138. }
  82139. }
  82140. });
  82141. };
  82142. return WebVRFreeCamera;
  82143. }(BABYLON.FreeCamera));
  82144. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82145. })(BABYLON || (BABYLON = {}));
  82146. //# sourceMappingURL=babylon.webVRCamera.js.map
  82147. "use strict";
  82148. var BABYLON;
  82149. (function (BABYLON) {
  82150. // We're mainly based on the logic defined into the FreeCamera code
  82151. /**
  82152. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82153. * being tilted forward or back and left or right.
  82154. */
  82155. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82156. __extends(DeviceOrientationCamera, _super);
  82157. /**
  82158. * Creates a new device orientation camera. @see DeviceOrientationCamera
  82159. * @param name The name of the camera
  82160. * @param position The start position camera
  82161. * @param scene The scene the camera belongs to
  82162. */
  82163. function DeviceOrientationCamera(name, position, scene) {
  82164. var _this = _super.call(this, name, position, scene) || this;
  82165. _this._quaternionCache = new BABYLON.Quaternion();
  82166. _this.inputs.addDeviceOrientation();
  82167. return _this;
  82168. }
  82169. /**
  82170. * Gets the current instance class name ("DeviceOrientationCamera").
  82171. * This helps avoiding instanceof at run time.
  82172. * @returns the class name
  82173. */
  82174. DeviceOrientationCamera.prototype.getClassName = function () {
  82175. return "DeviceOrientationCamera";
  82176. };
  82177. /**
  82178. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82179. */
  82180. DeviceOrientationCamera.prototype._checkInputs = function () {
  82181. _super.prototype._checkInputs.call(this);
  82182. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82183. if (this._initialQuaternion) {
  82184. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82185. }
  82186. };
  82187. /**
  82188. * Reset the camera to its default orientation on the specified axis only.
  82189. * @param axis The axis to reset
  82190. */
  82191. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82192. var _this = this;
  82193. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82194. //can only work if this camera has a rotation quaternion already.
  82195. if (!this.rotationQuaternion)
  82196. return;
  82197. if (!this._initialQuaternion) {
  82198. this._initialQuaternion = new BABYLON.Quaternion();
  82199. }
  82200. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82201. ['x', 'y', 'z'].forEach(function (axisName) {
  82202. if (!axis[axisName]) {
  82203. _this._initialQuaternion[axisName] = 0;
  82204. }
  82205. else {
  82206. _this._initialQuaternion[axisName] *= -1;
  82207. }
  82208. });
  82209. this._initialQuaternion.normalize();
  82210. //force rotation update
  82211. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82212. };
  82213. return DeviceOrientationCamera;
  82214. }(BABYLON.FreeCamera));
  82215. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82216. })(BABYLON || (BABYLON = {}));
  82217. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82218. "use strict";
  82219. var BABYLON;
  82220. (function (BABYLON) {
  82221. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82222. __extends(VRDeviceOrientationFreeCamera, _super);
  82223. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82224. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82225. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82226. var _this = _super.call(this, name, position, scene) || this;
  82227. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82228. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82229. return _this;
  82230. }
  82231. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82232. return "VRDeviceOrientationFreeCamera";
  82233. };
  82234. return VRDeviceOrientationFreeCamera;
  82235. }(BABYLON.DeviceOrientationCamera));
  82236. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82237. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82238. __extends(VRDeviceOrientationGamepadCamera, _super);
  82239. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82240. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82241. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82242. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82243. _this.inputs.addGamepad();
  82244. return _this;
  82245. }
  82246. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82247. return "VRDeviceOrientationGamepadCamera";
  82248. };
  82249. return VRDeviceOrientationGamepadCamera;
  82250. }(VRDeviceOrientationFreeCamera));
  82251. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82252. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82253. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82254. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82255. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82256. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82257. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82258. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82259. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82260. _this.inputs.addVRDeviceOrientation();
  82261. return _this;
  82262. }
  82263. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82264. return "VRDeviceOrientationArcRotateCamera";
  82265. };
  82266. return VRDeviceOrientationArcRotateCamera;
  82267. }(BABYLON.ArcRotateCamera));
  82268. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82269. })(BABYLON || (BABYLON = {}));
  82270. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82271. "use strict";
  82272. var BABYLON;
  82273. (function (BABYLON) {
  82274. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82275. __extends(AnaglyphFreeCamera, _super);
  82276. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82277. var _this = _super.call(this, name, position, scene) || this;
  82278. _this.interaxialDistance = interaxialDistance;
  82279. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82280. return _this;
  82281. }
  82282. AnaglyphFreeCamera.prototype.getClassName = function () {
  82283. return "AnaglyphFreeCamera";
  82284. };
  82285. return AnaglyphFreeCamera;
  82286. }(BABYLON.FreeCamera));
  82287. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82288. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82289. __extends(AnaglyphArcRotateCamera, _super);
  82290. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82291. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82292. _this.interaxialDistance = interaxialDistance;
  82293. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82294. return _this;
  82295. }
  82296. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82297. return "AnaglyphArcRotateCamera";
  82298. };
  82299. return AnaglyphArcRotateCamera;
  82300. }(BABYLON.ArcRotateCamera));
  82301. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82302. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82303. __extends(AnaglyphGamepadCamera, _super);
  82304. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82305. var _this = _super.call(this, name, position, scene) || this;
  82306. _this.interaxialDistance = interaxialDistance;
  82307. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82308. return _this;
  82309. }
  82310. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82311. return "AnaglyphGamepadCamera";
  82312. };
  82313. return AnaglyphGamepadCamera;
  82314. }(BABYLON.GamepadCamera));
  82315. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82316. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82317. __extends(AnaglyphUniversalCamera, _super);
  82318. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82319. var _this = _super.call(this, name, position, scene) || this;
  82320. _this.interaxialDistance = interaxialDistance;
  82321. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82322. return _this;
  82323. }
  82324. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82325. return "AnaglyphUniversalCamera";
  82326. };
  82327. return AnaglyphUniversalCamera;
  82328. }(BABYLON.UniversalCamera));
  82329. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82330. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82331. __extends(StereoscopicFreeCamera, _super);
  82332. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82333. var _this = _super.call(this, name, position, scene) || this;
  82334. _this.interaxialDistance = interaxialDistance;
  82335. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82336. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82337. return _this;
  82338. }
  82339. StereoscopicFreeCamera.prototype.getClassName = function () {
  82340. return "StereoscopicFreeCamera";
  82341. };
  82342. return StereoscopicFreeCamera;
  82343. }(BABYLON.FreeCamera));
  82344. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82345. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82346. __extends(StereoscopicArcRotateCamera, _super);
  82347. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82348. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82349. _this.interaxialDistance = interaxialDistance;
  82350. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82351. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82352. return _this;
  82353. }
  82354. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82355. return "StereoscopicArcRotateCamera";
  82356. };
  82357. return StereoscopicArcRotateCamera;
  82358. }(BABYLON.ArcRotateCamera));
  82359. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82360. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82361. __extends(StereoscopicGamepadCamera, _super);
  82362. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82363. var _this = _super.call(this, name, position, scene) || this;
  82364. _this.interaxialDistance = interaxialDistance;
  82365. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82366. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82367. return _this;
  82368. }
  82369. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82370. return "StereoscopicGamepadCamera";
  82371. };
  82372. return StereoscopicGamepadCamera;
  82373. }(BABYLON.GamepadCamera));
  82374. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82375. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82376. __extends(StereoscopicUniversalCamera, _super);
  82377. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82378. var _this = _super.call(this, name, position, scene) || this;
  82379. _this.interaxialDistance = interaxialDistance;
  82380. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82381. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82382. return _this;
  82383. }
  82384. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82385. return "StereoscopicUniversalCamera";
  82386. };
  82387. return StereoscopicUniversalCamera;
  82388. }(BABYLON.UniversalCamera));
  82389. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82390. })(BABYLON || (BABYLON = {}));
  82391. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82392. "use strict";
  82393. var BABYLON;
  82394. (function (BABYLON) {
  82395. var VRExperienceHelperGazer = /** @class */ (function () {
  82396. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82397. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82398. this.scene = scene;
  82399. this._pointerDownOnMeshAsked = false;
  82400. this._isActionableMesh = false;
  82401. this._teleportationRequestInitiated = false;
  82402. this._teleportationBackRequestInitiated = false;
  82403. this._dpadPressed = true;
  82404. this._activePointer = false;
  82405. this._id = VRExperienceHelperGazer._idCounter++;
  82406. // Gaze tracker
  82407. if (!gazeTrackerToClone) {
  82408. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82409. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82410. this._gazeTracker.isPickable = false;
  82411. this._gazeTracker.isVisible = false;
  82412. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82413. targetMat.specularColor = BABYLON.Color3.Black();
  82414. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82415. targetMat.backFaceCulling = false;
  82416. this._gazeTracker.material = targetMat;
  82417. }
  82418. else {
  82419. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82420. }
  82421. }
  82422. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82423. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82424. };
  82425. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82426. this._pointerDownOnMeshAsked = true;
  82427. if (this._currentMeshSelected && this._currentHit) {
  82428. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82429. }
  82430. };
  82431. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82432. if (this._currentMeshSelected && this._currentHit) {
  82433. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82434. }
  82435. this._pointerDownOnMeshAsked = false;
  82436. };
  82437. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82438. this._activePointer = true;
  82439. };
  82440. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82441. this._activePointer = false;
  82442. };
  82443. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82444. };
  82445. VRExperienceHelperGazer.prototype.dispose = function () {
  82446. this._interactionsEnabled = false;
  82447. this._teleportationEnabled = false;
  82448. };
  82449. VRExperienceHelperGazer._idCounter = 0;
  82450. return VRExperienceHelperGazer;
  82451. }());
  82452. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82453. __extends(VRExperienceHelperControllerGazer, _super);
  82454. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82455. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82456. _this.webVRController = webVRController;
  82457. // Laser pointer
  82458. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82459. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82460. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82461. laserPointerMaterial.alpha = 0.6;
  82462. _this._laserPointer.material = laserPointerMaterial;
  82463. _this._laserPointer.rotation.x = Math.PI / 2;
  82464. _this._laserPointer.position.z = -0.5;
  82465. _this._laserPointer.isVisible = false;
  82466. if (!webVRController.mesh) {
  82467. // Create an empty mesh that is used prior to loading the high quality model
  82468. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82469. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82470. preloadPointerPose.rotation.x = -0.7;
  82471. preloadMesh.addChild(preloadPointerPose);
  82472. webVRController.attachToMesh(preloadMesh);
  82473. }
  82474. _this._setLaserPointerParent(webVRController.mesh);
  82475. return _this;
  82476. }
  82477. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82478. return this.webVRController.getForwardRay(length);
  82479. };
  82480. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82481. _super.prototype._activatePointer.call(this);
  82482. this._laserPointer.isVisible = true;
  82483. };
  82484. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82485. _super.prototype._deactivatePointer.call(this);
  82486. this._laserPointer.isVisible = false;
  82487. };
  82488. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82489. this._laserPointer.material.emissiveColor = color;
  82490. };
  82491. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82492. var makeNotPick = function (root) {
  82493. root.name += " laserPointer";
  82494. root.getChildMeshes().forEach(function (c) {
  82495. makeNotPick(c);
  82496. });
  82497. };
  82498. makeNotPick(mesh);
  82499. var childMeshes = mesh.getChildMeshes();
  82500. this.webVRController._pointingPoseNode = null;
  82501. for (var i = 0; i < childMeshes.length; i++) {
  82502. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82503. mesh = childMeshes[i];
  82504. this.webVRController._pointingPoseNode = mesh;
  82505. break;
  82506. }
  82507. }
  82508. this._laserPointer.parent = mesh;
  82509. };
  82510. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82511. this._laserPointer.scaling.y = distance;
  82512. this._laserPointer.position.z = -distance / 2;
  82513. };
  82514. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82515. _super.prototype.dispose.call(this);
  82516. this._laserPointer.dispose();
  82517. };
  82518. return VRExperienceHelperControllerGazer;
  82519. }(VRExperienceHelperGazer));
  82520. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82521. __extends(VRExperienceHelperCameraGazer, _super);
  82522. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82523. var _this = _super.call(this, scene) || this;
  82524. _this.getCamera = getCamera;
  82525. return _this;
  82526. }
  82527. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82528. var camera = this.getCamera();
  82529. if (camera) {
  82530. return camera.getForwardRay(length);
  82531. }
  82532. else {
  82533. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82534. }
  82535. };
  82536. return VRExperienceHelperCameraGazer;
  82537. }(VRExperienceHelperGazer));
  82538. /**
  82539. * Helps to quickly add VR support to an existing scene.
  82540. * See http://doc.babylonjs.com/how_to/webvr_helper
  82541. */
  82542. var VRExperienceHelper = /** @class */ (function () {
  82543. /**
  82544. * Instantiates a VRExperienceHelper.
  82545. * Helps to quickly add VR support to an existing scene.
  82546. * @param scene The scene the VRExperienceHelper belongs to.
  82547. * @param webVROptions Options to modify the vr experience helper's behavior.
  82548. */
  82549. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82550. if (webVROptions === void 0) { webVROptions = {}; }
  82551. var _this = this;
  82552. this.webVROptions = webVROptions;
  82553. // Can the system support WebVR, even if a headset isn't plugged in?
  82554. this._webVRsupported = false;
  82555. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82556. this._webVRready = false;
  82557. // Are we waiting for the requestPresent callback to complete?
  82558. this._webVRrequesting = false;
  82559. // Are we presenting to the headset right now?
  82560. this._webVRpresenting = false;
  82561. // Are we presenting in the fullscreen fallback?
  82562. this._fullscreenVRpresenting = false;
  82563. /**
  82564. * Observable raised when entering VR.
  82565. */
  82566. this.onEnteringVRObservable = new BABYLON.Observable();
  82567. /**
  82568. * Observable raised when exiting VR.
  82569. */
  82570. this.onExitingVRObservable = new BABYLON.Observable();
  82571. /**
  82572. * Observable raised when controller mesh is loaded.
  82573. */
  82574. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82575. this._useCustomVRButton = false;
  82576. this._teleportationRequested = false;
  82577. this._teleportActive = false;
  82578. this._floorMeshesCollection = [];
  82579. this._rotationAllowed = true;
  82580. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82581. this._rotationRightAsked = false;
  82582. this._rotationLeftAsked = false;
  82583. this._isDefaultTeleportationTarget = true;
  82584. this._teleportationFillColor = "#444444";
  82585. this._teleportationBorderColor = "#FFFFFF";
  82586. this._rotationAngle = 0;
  82587. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82588. this._padSensibilityUp = 0.65;
  82589. this._padSensibilityDown = 0.35;
  82590. this.leftController = null;
  82591. this.rightController = null;
  82592. /**
  82593. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82594. */
  82595. this.onNewMeshSelected = new BABYLON.Observable();
  82596. /**
  82597. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82598. */
  82599. this.onNewMeshPicked = new BABYLON.Observable();
  82600. /**
  82601. * Observable raised before camera teleportation
  82602. */
  82603. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82604. /**
  82605. * Observable raised after camera teleportation
  82606. */
  82607. this.onAfterCameraTeleport = new BABYLON.Observable();
  82608. /**
  82609. * Observable raised when current selected mesh gets unselected
  82610. */
  82611. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82612. /**
  82613. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82614. */
  82615. this.teleportationEnabled = true;
  82616. this._teleportationInitialized = false;
  82617. this._interactionsEnabled = false;
  82618. this._interactionsRequested = false;
  82619. this._displayGaze = true;
  82620. this._displayLaserPointer = true;
  82621. this._onResize = function () {
  82622. _this.moveButtonToBottomRight();
  82623. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82624. _this.exitVR();
  82625. }
  82626. };
  82627. this._onFullscreenChange = function () {
  82628. if (document.fullscreen !== undefined) {
  82629. _this._fullscreenVRpresenting = document.fullscreen;
  82630. }
  82631. else if (document.mozFullScreen !== undefined) {
  82632. _this._fullscreenVRpresenting = document.mozFullScreen;
  82633. }
  82634. else if (document.webkitIsFullScreen !== undefined) {
  82635. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82636. }
  82637. else if (document.msIsFullScreen !== undefined) {
  82638. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82639. }
  82640. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82641. _this.exitVR();
  82642. if (!_this._useCustomVRButton) {
  82643. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82644. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82645. }
  82646. }
  82647. };
  82648. this.beforeRender = function () {
  82649. if (_this.leftController && _this.leftController._activePointer) {
  82650. _this._castRayAndSelectObject(_this.leftController);
  82651. }
  82652. if (_this.rightController && _this.rightController._activePointer) {
  82653. _this._castRayAndSelectObject(_this.rightController);
  82654. }
  82655. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82656. _this._castRayAndSelectObject(_this._cameraGazer);
  82657. }
  82658. else {
  82659. _this._cameraGazer._gazeTracker.isVisible = false;
  82660. }
  82661. };
  82662. this._onNewGamepadConnected = function (gamepad) {
  82663. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82664. if (gamepad.leftStick) {
  82665. gamepad.onleftstickchanged(function (stickValues) {
  82666. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82667. // Listening to classic/xbox gamepad only if no VR controller is active
  82668. if ((!_this.leftController && !_this.rightController) ||
  82669. ((_this.leftController && !_this.leftController._activePointer) &&
  82670. (_this.rightController && !_this.rightController._activePointer))) {
  82671. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82672. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82673. }
  82674. }
  82675. });
  82676. }
  82677. if (gamepad.rightStick) {
  82678. gamepad.onrightstickchanged(function (stickValues) {
  82679. if (_this._teleportationInitialized) {
  82680. _this._checkRotate(stickValues, _this._cameraGazer);
  82681. }
  82682. });
  82683. }
  82684. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82685. gamepad.onbuttondown(function (buttonPressed) {
  82686. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82687. _this._cameraGazer._selectionPointerDown();
  82688. }
  82689. });
  82690. gamepad.onbuttonup(function (buttonPressed) {
  82691. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82692. _this._cameraGazer._selectionPointerUp();
  82693. }
  82694. });
  82695. }
  82696. }
  82697. else {
  82698. var webVRController = gamepad;
  82699. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  82700. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  82701. _this.rightController = controller;
  82702. }
  82703. else {
  82704. _this.leftController = controller;
  82705. }
  82706. _this._tryEnableInteractionOnController(controller);
  82707. }
  82708. };
  82709. // 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
  82710. this._tryEnableInteractionOnController = function (controller) {
  82711. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82712. _this._enableInteractionOnController(controller);
  82713. }
  82714. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82715. _this._enableTeleportationOnController(controller);
  82716. }
  82717. };
  82718. this._onNewGamepadDisconnected = function (gamepad) {
  82719. if (gamepad instanceof BABYLON.WebVRController) {
  82720. if (gamepad.hand === "left" && _this.leftController != null) {
  82721. _this.leftController.dispose();
  82722. _this.leftController = null;
  82723. }
  82724. if (gamepad.hand === "right" && _this.rightController != null) {
  82725. _this.rightController.dispose();
  82726. _this.rightController = null;
  82727. }
  82728. }
  82729. };
  82730. this._workingVector = BABYLON.Vector3.Zero();
  82731. this._workingQuaternion = BABYLON.Quaternion.Identity();
  82732. this._workingMatrix = BABYLON.Matrix.Identity();
  82733. this._scene = scene;
  82734. this._canvas = scene.getEngine().getRenderingCanvas();
  82735. // Parse options
  82736. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  82737. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  82738. }
  82739. if (webVROptions.createDeviceOrientationCamera === undefined) {
  82740. webVROptions.createDeviceOrientationCamera = true;
  82741. }
  82742. if (webVROptions.defaultHeight === undefined) {
  82743. webVROptions.defaultHeight = 1.7;
  82744. }
  82745. if (webVROptions.useCustomVRButton) {
  82746. this._useCustomVRButton = true;
  82747. if (webVROptions.customVRButton) {
  82748. this._btnVR = webVROptions.customVRButton;
  82749. }
  82750. }
  82751. if (webVROptions.rayLength) {
  82752. this._rayLength = webVROptions.rayLength;
  82753. }
  82754. this._defaultHeight = webVROptions.defaultHeight;
  82755. if (webVROptions.positionScale) {
  82756. this._rayLength *= webVROptions.positionScale;
  82757. this._defaultHeight *= webVROptions.positionScale;
  82758. }
  82759. // Set position
  82760. if (this._scene.activeCamera) {
  82761. this._position = this._scene.activeCamera.position.clone();
  82762. }
  82763. else {
  82764. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  82765. }
  82766. // Set non-vr camera
  82767. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  82768. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  82769. // Copy data from existing camera
  82770. if (this._scene.activeCamera) {
  82771. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  82772. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  82773. // Set rotation from previous camera
  82774. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  82775. var targetCamera = this._scene.activeCamera;
  82776. if (targetCamera.rotationQuaternion) {
  82777. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  82778. }
  82779. else {
  82780. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82781. }
  82782. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82783. }
  82784. }
  82785. this._scene.activeCamera = this._deviceOrientationCamera;
  82786. if (this._canvas) {
  82787. this._scene.activeCamera.attachControl(this._canvas);
  82788. }
  82789. }
  82790. else {
  82791. this._existingCamera = this._scene.activeCamera;
  82792. }
  82793. // Create VR cameras
  82794. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82795. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82796. }
  82797. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82798. this._webVRCamera.useStandingMatrix();
  82799. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82800. // Create default button
  82801. if (!this._useCustomVRButton) {
  82802. this._btnVR = document.createElement("BUTTON");
  82803. this._btnVR.className = "babylonVRicon";
  82804. this._btnVR.id = "babylonVRiconbtn";
  82805. this._btnVR.title = "Click to switch to VR";
  82806. 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) }";
  82807. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82808. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82809. // css += ".babylonVRicon.vrdisplaysupported { }";
  82810. // css += ".babylonVRicon.vrdisplayready { }";
  82811. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82812. var style = document.createElement('style');
  82813. style.appendChild(document.createTextNode(css));
  82814. document.getElementsByTagName('head')[0].appendChild(style);
  82815. this.moveButtonToBottomRight();
  82816. }
  82817. // VR button click event
  82818. if (this._btnVR) {
  82819. this._btnVR.addEventListener("click", function () {
  82820. if (!_this.isInVRMode) {
  82821. _this.enterVR();
  82822. }
  82823. else {
  82824. _this.exitVR();
  82825. }
  82826. });
  82827. }
  82828. // Window events
  82829. window.addEventListener("resize", this._onResize);
  82830. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82831. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82832. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82833. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82834. // Display vr button when headset is connected
  82835. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82836. this.displayVRButton();
  82837. }
  82838. else {
  82839. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82840. if (e.vrDisplay) {
  82841. _this.displayVRButton();
  82842. }
  82843. });
  82844. }
  82845. // Exiting VR mode using 'ESC' key on desktop
  82846. this._onKeyDown = function (event) {
  82847. if (event.keyCode === 27 && _this.isInVRMode) {
  82848. _this.exitVR();
  82849. }
  82850. };
  82851. document.addEventListener("keydown", this._onKeyDown);
  82852. // Exiting VR mode double tapping the touch screen
  82853. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82854. if (_this.isInVRMode) {
  82855. _this.exitVR();
  82856. if (_this._fullscreenVRpresenting) {
  82857. _this._scene.getEngine().switchFullscreen(true);
  82858. }
  82859. }
  82860. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82861. // Listen for WebVR display changes
  82862. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82863. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82864. this._onVRRequestPresentStart = function () {
  82865. _this._webVRrequesting = true;
  82866. _this.updateButtonVisibility();
  82867. };
  82868. this._onVRRequestPresentComplete = function (success) {
  82869. _this._webVRrequesting = false;
  82870. _this.updateButtonVisibility();
  82871. };
  82872. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82873. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82874. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82875. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82876. scene.onDisposeObservable.add(function () {
  82877. _this.dispose();
  82878. });
  82879. // Gamepad connection events
  82880. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82881. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82882. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82883. this.updateButtonVisibility();
  82884. //create easing functions
  82885. this._circleEase = new BABYLON.CircleEase();
  82886. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82887. }
  82888. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82889. /** Return this.onEnteringVRObservable
  82890. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82891. */
  82892. get: function () {
  82893. return this.onEnteringVRObservable;
  82894. },
  82895. enumerable: true,
  82896. configurable: true
  82897. });
  82898. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82899. /** Return this.onExitingVRObservable
  82900. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82901. */
  82902. get: function () {
  82903. return this.onExitingVRObservable;
  82904. },
  82905. enumerable: true,
  82906. configurable: true
  82907. });
  82908. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82909. /** Return this.onControllerMeshLoadedObservable
  82910. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82911. */
  82912. get: function () {
  82913. return this.onControllerMeshLoadedObservable;
  82914. },
  82915. enumerable: true,
  82916. configurable: true
  82917. });
  82918. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82919. /**
  82920. * The mesh used to display where the user is going to teleport.
  82921. */
  82922. get: function () {
  82923. return this._teleportationTarget;
  82924. },
  82925. /**
  82926. * Sets the mesh to be used to display where the user is going to teleport.
  82927. */
  82928. set: function (value) {
  82929. if (value) {
  82930. value.name = "teleportationTarget";
  82931. this._isDefaultTeleportationTarget = false;
  82932. this._teleportationTarget = value;
  82933. }
  82934. },
  82935. enumerable: true,
  82936. configurable: true
  82937. });
  82938. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82939. /**
  82940. * The mesh used to display where the user is selecting,
  82941. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82942. * See http://doc.babylonjs.com/resources/baking_transformations
  82943. */
  82944. get: function () {
  82945. return this._cameraGazer._gazeTracker;
  82946. },
  82947. set: function (value) {
  82948. if (value) {
  82949. this._cameraGazer._gazeTracker = value;
  82950. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82951. this._cameraGazer._gazeTracker.isPickable = false;
  82952. this._cameraGazer._gazeTracker.isVisible = false;
  82953. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82954. if (this.leftController) {
  82955. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82956. }
  82957. if (this.rightController) {
  82958. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82959. }
  82960. }
  82961. },
  82962. enumerable: true,
  82963. configurable: true
  82964. });
  82965. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82966. /**
  82967. * If the ray of the gaze should be displayed.
  82968. */
  82969. get: function () {
  82970. return this._displayGaze;
  82971. },
  82972. /**
  82973. * Sets if the ray of the gaze should be displayed.
  82974. */
  82975. set: function (value) {
  82976. this._displayGaze = value;
  82977. if (!value) {
  82978. this._cameraGazer._gazeTracker.isVisible = false;
  82979. if (this.leftController) {
  82980. this.leftController._gazeTracker.isVisible = false;
  82981. }
  82982. if (this.rightController) {
  82983. this.rightController._gazeTracker.isVisible = false;
  82984. }
  82985. }
  82986. },
  82987. enumerable: true,
  82988. configurable: true
  82989. });
  82990. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82991. /**
  82992. * If the ray of the LaserPointer should be displayed.
  82993. */
  82994. get: function () {
  82995. return this._displayLaserPointer;
  82996. },
  82997. /**
  82998. * Sets if the ray of the LaserPointer should be displayed.
  82999. */
  83000. set: function (value) {
  83001. this._displayLaserPointer = value;
  83002. if (!value) {
  83003. if (this.rightController) {
  83004. this.rightController._deactivatePointer();
  83005. this.rightController._gazeTracker.isVisible = false;
  83006. }
  83007. if (this.leftController) {
  83008. this.leftController._deactivatePointer();
  83009. this.leftController._gazeTracker.isVisible = false;
  83010. }
  83011. }
  83012. else {
  83013. if (this.rightController) {
  83014. this.rightController._activatePointer();
  83015. }
  83016. else if (this.leftController) {
  83017. this.leftController._activatePointer();
  83018. }
  83019. }
  83020. },
  83021. enumerable: true,
  83022. configurable: true
  83023. });
  83024. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  83025. /**
  83026. * The deviceOrientationCamera used as the camera when not in VR.
  83027. */
  83028. get: function () {
  83029. return this._deviceOrientationCamera;
  83030. },
  83031. enumerable: true,
  83032. configurable: true
  83033. });
  83034. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  83035. /**
  83036. * Based on the current WebVR support, returns the current VR camera used.
  83037. */
  83038. get: function () {
  83039. if (this._webVRready) {
  83040. return this._webVRCamera;
  83041. }
  83042. else {
  83043. return this._scene.activeCamera;
  83044. }
  83045. },
  83046. enumerable: true,
  83047. configurable: true
  83048. });
  83049. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83050. /**
  83051. * The webVRCamera which is used when in VR.
  83052. */
  83053. get: function () {
  83054. return this._webVRCamera;
  83055. },
  83056. enumerable: true,
  83057. configurable: true
  83058. });
  83059. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83060. /**
  83061. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83062. */
  83063. get: function () {
  83064. return this._vrDeviceOrientationCamera;
  83065. },
  83066. enumerable: true,
  83067. configurable: true
  83068. });
  83069. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83070. get: function () {
  83071. var result = this._cameraGazer._teleportationRequestInitiated
  83072. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83073. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83074. return result;
  83075. },
  83076. enumerable: true,
  83077. configurable: true
  83078. });
  83079. // Raised when one of the controller has loaded successfully its associated default mesh
  83080. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83081. if (this.leftController && this.leftController.webVRController == webVRController) {
  83082. if (webVRController.mesh) {
  83083. this.leftController._setLaserPointerParent(webVRController.mesh);
  83084. }
  83085. }
  83086. if (this.rightController && this.rightController.webVRController == webVRController) {
  83087. if (webVRController.mesh) {
  83088. this.rightController._setLaserPointerParent(webVRController.mesh);
  83089. }
  83090. }
  83091. try {
  83092. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83093. }
  83094. catch (err) {
  83095. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83096. }
  83097. };
  83098. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83099. /**
  83100. * Gets a value indicating if we are currently in VR mode.
  83101. */
  83102. get: function () {
  83103. return this._webVRpresenting || this._fullscreenVRpresenting;
  83104. },
  83105. enumerable: true,
  83106. configurable: true
  83107. });
  83108. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83109. var vrDisplay = this._scene.getEngine().getVRDevice();
  83110. if (vrDisplay) {
  83111. var wasPresenting = this._webVRpresenting;
  83112. // A VR display is connected
  83113. this._webVRpresenting = vrDisplay.isPresenting;
  83114. if (wasPresenting && !this._webVRpresenting)
  83115. this.exitVR();
  83116. }
  83117. else {
  83118. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83119. }
  83120. this.updateButtonVisibility();
  83121. };
  83122. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83123. this._webVRsupported = eventArgs.vrSupported;
  83124. this._webVRready = !!eventArgs.vrDisplay;
  83125. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83126. this.updateButtonVisibility();
  83127. };
  83128. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83129. if (this._canvas && !this._useCustomVRButton) {
  83130. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83131. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83132. }
  83133. };
  83134. VRExperienceHelper.prototype.displayVRButton = function () {
  83135. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83136. document.body.appendChild(this._btnVR);
  83137. this._btnVRDisplayed = true;
  83138. }
  83139. };
  83140. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83141. if (!this._btnVR || this._useCustomVRButton) {
  83142. return;
  83143. }
  83144. this._btnVR.className = "babylonVRicon";
  83145. if (this.isInVRMode) {
  83146. this._btnVR.className += " vrdisplaypresenting";
  83147. }
  83148. else {
  83149. if (this._webVRready)
  83150. this._btnVR.className += " vrdisplayready";
  83151. if (this._webVRsupported)
  83152. this._btnVR.className += " vrdisplaysupported";
  83153. if (this._webVRrequesting)
  83154. this._btnVR.className += " vrdisplayrequesting";
  83155. }
  83156. };
  83157. /**
  83158. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83159. * Otherwise, will use the fullscreen API.
  83160. */
  83161. VRExperienceHelper.prototype.enterVR = function () {
  83162. if (this.onEnteringVRObservable) {
  83163. try {
  83164. this.onEnteringVRObservable.notifyObservers(this);
  83165. }
  83166. catch (err) {
  83167. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83168. }
  83169. }
  83170. if (this._scene.activeCamera) {
  83171. this._position = this._scene.activeCamera.position.clone();
  83172. // make sure that we return to the last active camera
  83173. this._existingCamera = this._scene.activeCamera;
  83174. }
  83175. if (this._webVRrequesting)
  83176. return;
  83177. // If WebVR is supported and a headset is connected
  83178. if (this._webVRready) {
  83179. if (!this._webVRpresenting) {
  83180. this._webVRCamera.position = this._position;
  83181. this._scene.activeCamera = this._webVRCamera;
  83182. }
  83183. }
  83184. else if (this._vrDeviceOrientationCamera) {
  83185. this._vrDeviceOrientationCamera.position = this._position;
  83186. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83187. this._scene.getEngine().switchFullscreen(true);
  83188. this.updateButtonVisibility();
  83189. }
  83190. if (this._scene.activeCamera && this._canvas) {
  83191. this._scene.activeCamera.attachControl(this._canvas);
  83192. }
  83193. if (this._interactionsEnabled) {
  83194. this._scene.registerBeforeRender(this.beforeRender);
  83195. }
  83196. };
  83197. /**
  83198. * Attempt to exit VR, or fullscreen.
  83199. */
  83200. VRExperienceHelper.prototype.exitVR = function () {
  83201. if (this.onExitingVRObservable) {
  83202. try {
  83203. this.onExitingVRObservable.notifyObservers(this);
  83204. }
  83205. catch (err) {
  83206. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83207. }
  83208. }
  83209. if (this._webVRpresenting) {
  83210. this._scene.getEngine().disableVR();
  83211. }
  83212. if (this._scene.activeCamera) {
  83213. this._position = this._scene.activeCamera.position.clone();
  83214. }
  83215. if (this._deviceOrientationCamera) {
  83216. this._deviceOrientationCamera.position = this._position;
  83217. this._scene.activeCamera = this._deviceOrientationCamera;
  83218. if (this._canvas) {
  83219. this._scene.activeCamera.attachControl(this._canvas);
  83220. }
  83221. }
  83222. else if (this._existingCamera) {
  83223. this._existingCamera.position = this._position;
  83224. this._scene.activeCamera = this._existingCamera;
  83225. }
  83226. this.updateButtonVisibility();
  83227. if (this._interactionsEnabled) {
  83228. this._scene.unregisterBeforeRender(this.beforeRender);
  83229. }
  83230. };
  83231. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83232. /**
  83233. * The position of the vr experience helper.
  83234. */
  83235. get: function () {
  83236. return this._position;
  83237. },
  83238. /**
  83239. * Sets the position of the vr experience helper.
  83240. */
  83241. set: function (value) {
  83242. this._position = value;
  83243. if (this._scene.activeCamera) {
  83244. this._scene.activeCamera.position = value;
  83245. }
  83246. },
  83247. enumerable: true,
  83248. configurable: true
  83249. });
  83250. /**
  83251. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83252. */
  83253. VRExperienceHelper.prototype.enableInteractions = function () {
  83254. var _this = this;
  83255. if (!this._interactionsEnabled) {
  83256. this._interactionsRequested = true;
  83257. if (this.leftController) {
  83258. this._enableInteractionOnController(this.leftController);
  83259. }
  83260. if (this.rightController) {
  83261. this._enableInteractionOnController(this.rightController);
  83262. }
  83263. this.raySelectionPredicate = function (mesh) {
  83264. return mesh.isVisible;
  83265. };
  83266. this.meshSelectionPredicate = function (mesh) {
  83267. return true;
  83268. };
  83269. this._raySelectionPredicate = function (mesh) {
  83270. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83271. && mesh.name.indexOf("teleportationTarget") === -1
  83272. && mesh.name.indexOf("torusTeleportation") === -1
  83273. && mesh.name.indexOf("laserPointer") === -1)) {
  83274. return _this.raySelectionPredicate(mesh);
  83275. }
  83276. return false;
  83277. };
  83278. this._interactionsEnabled = true;
  83279. }
  83280. };
  83281. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83282. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83283. if (this._floorMeshesCollection[i].id === mesh.id) {
  83284. return true;
  83285. }
  83286. }
  83287. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83288. return true;
  83289. }
  83290. return false;
  83291. };
  83292. /**
  83293. * Adds a floor mesh to be used for teleportation.
  83294. * @param floorMesh the mesh to be used for teleportation.
  83295. */
  83296. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83297. if (!this._floorMeshesCollection) {
  83298. return;
  83299. }
  83300. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83301. return;
  83302. }
  83303. this._floorMeshesCollection.push(floorMesh);
  83304. };
  83305. /**
  83306. * Removes a floor mesh from being used for teleportation.
  83307. * @param floorMesh the mesh to be removed.
  83308. */
  83309. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83310. if (!this._floorMeshesCollection) {
  83311. return;
  83312. }
  83313. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83314. if (meshIndex !== -1) {
  83315. this._floorMeshesCollection.splice(meshIndex, 1);
  83316. }
  83317. };
  83318. /**
  83319. * Enables interactions and teleportation using the VR controllers and gaze.
  83320. * @param vrTeleportationOptions options to modify teleportation behavior.
  83321. */
  83322. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83323. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83324. if (!this._teleportationInitialized) {
  83325. this._teleportationRequested = true;
  83326. this.enableInteractions();
  83327. if (vrTeleportationOptions.floorMeshName) {
  83328. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83329. }
  83330. if (vrTeleportationOptions.floorMeshes) {
  83331. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83332. }
  83333. if (this.leftController != null) {
  83334. this._enableTeleportationOnController(this.leftController);
  83335. }
  83336. if (this.rightController != null) {
  83337. this._enableTeleportationOnController(this.rightController);
  83338. }
  83339. // Creates an image processing post process for the vignette not relying
  83340. // on the main scene configuration for image processing to reduce setup and spaces
  83341. // (gamma/linear) conflicts.
  83342. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83343. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83344. imageProcessingConfiguration.vignetteEnabled = true;
  83345. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83346. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83347. this._teleportationInitialized = true;
  83348. if (this._isDefaultTeleportationTarget) {
  83349. this._createTeleportationCircles();
  83350. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83351. }
  83352. }
  83353. };
  83354. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83355. var _this = this;
  83356. var controllerMesh = controller.webVRController.mesh;
  83357. if (controllerMesh) {
  83358. controller._interactionsEnabled = true;
  83359. controller._activatePointer();
  83360. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83361. // Enabling / disabling laserPointer
  83362. if (_this._displayLaserPointer && stateObject.value === 1) {
  83363. if (controller._activePointer) {
  83364. controller._deactivatePointer();
  83365. }
  83366. else {
  83367. controller._activatePointer();
  83368. }
  83369. if (_this.displayGaze) {
  83370. controller._gazeTracker.isVisible = controller._activePointer;
  83371. }
  83372. }
  83373. });
  83374. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83375. if (!controller._pointerDownOnMeshAsked) {
  83376. if (stateObject.value > _this._padSensibilityUp) {
  83377. controller._selectionPointerDown();
  83378. }
  83379. }
  83380. else if (stateObject.value < _this._padSensibilityDown) {
  83381. controller._selectionPointerUp();
  83382. }
  83383. });
  83384. }
  83385. };
  83386. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83387. // Dont teleport if another gaze already requested teleportation
  83388. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83389. return;
  83390. }
  83391. if (!gazer._teleportationRequestInitiated) {
  83392. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83393. gazer._activatePointer();
  83394. gazer._teleportationRequestInitiated = true;
  83395. }
  83396. }
  83397. else {
  83398. // Listening to the proper controller values changes to confirm teleportation
  83399. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83400. if (this._teleportActive) {
  83401. this._teleportCamera(this._haloCenter);
  83402. }
  83403. gazer._teleportationRequestInitiated = false;
  83404. }
  83405. }
  83406. };
  83407. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83408. // Only rotate when user is not currently selecting a teleportation location
  83409. if (gazer._teleportationRequestInitiated) {
  83410. return;
  83411. }
  83412. if (!this._rotationLeftAsked) {
  83413. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83414. this._rotationLeftAsked = true;
  83415. if (this._rotationAllowed) {
  83416. this._rotateCamera(false);
  83417. }
  83418. }
  83419. }
  83420. else {
  83421. if (stateObject.x > -this._padSensibilityDown) {
  83422. this._rotationLeftAsked = false;
  83423. }
  83424. }
  83425. if (!this._rotationRightAsked) {
  83426. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83427. this._rotationRightAsked = true;
  83428. if (this._rotationAllowed) {
  83429. this._rotateCamera(true);
  83430. }
  83431. }
  83432. }
  83433. else {
  83434. if (stateObject.x < this._padSensibilityDown) {
  83435. this._rotationRightAsked = false;
  83436. }
  83437. }
  83438. };
  83439. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83440. // Only teleport backwards when user is not currently selecting a teleportation location
  83441. if (gazer._teleportationRequestInitiated) {
  83442. return;
  83443. }
  83444. // Teleport backwards
  83445. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83446. if (!gazer._teleportationBackRequestInitiated) {
  83447. if (!this.currentVRCamera) {
  83448. return;
  83449. }
  83450. // Get rotation and position of the current camera
  83451. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83452. var position = this.currentVRCamera.position;
  83453. // If the camera has device position, use that instead
  83454. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83455. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83456. position = this.currentVRCamera.devicePosition;
  83457. }
  83458. // Get matrix with only the y rotation of the device rotation
  83459. rotation.toEulerAnglesToRef(this._workingVector);
  83460. this._workingVector.z = 0;
  83461. this._workingVector.x = 0;
  83462. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83463. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83464. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83465. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83466. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83467. var ray = new BABYLON.Ray(position, this._workingVector);
  83468. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83469. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83470. this._teleportCamera(hit.pickedPoint);
  83471. }
  83472. gazer._teleportationBackRequestInitiated = true;
  83473. }
  83474. }
  83475. else {
  83476. gazer._teleportationBackRequestInitiated = false;
  83477. }
  83478. };
  83479. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83480. var _this = this;
  83481. var controllerMesh = controller.webVRController.mesh;
  83482. if (controllerMesh) {
  83483. if (!controller._interactionsEnabled) {
  83484. this._enableInteractionOnController(controller);
  83485. }
  83486. controller._interactionsEnabled = true;
  83487. controller._teleportationEnabled = true;
  83488. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83489. controller._dpadPressed = false;
  83490. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83491. controller._dpadPressed = stateObject.pressed;
  83492. if (!controller._dpadPressed) {
  83493. _this._rotationLeftAsked = false;
  83494. _this._rotationRightAsked = false;
  83495. controller._teleportationBackRequestInitiated = false;
  83496. }
  83497. });
  83498. }
  83499. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83500. if (_this.teleportationEnabled) {
  83501. _this._checkTeleportBackwards(stateObject, controller);
  83502. _this._checkTeleportWithRay(stateObject, controller);
  83503. }
  83504. _this._checkRotate(stateObject, controller);
  83505. });
  83506. }
  83507. };
  83508. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83509. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83510. this._teleportationTarget.isPickable = false;
  83511. var length = 512;
  83512. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83513. dynamicTexture.hasAlpha = true;
  83514. var context = dynamicTexture.getContext();
  83515. var centerX = length / 2;
  83516. var centerY = length / 2;
  83517. var radius = 200;
  83518. context.beginPath();
  83519. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83520. context.fillStyle = this._teleportationFillColor;
  83521. context.fill();
  83522. context.lineWidth = 10;
  83523. context.strokeStyle = this._teleportationBorderColor;
  83524. context.stroke();
  83525. context.closePath();
  83526. dynamicTexture.update();
  83527. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83528. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83529. this._teleportationTarget.material = teleportationCircleMaterial;
  83530. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83531. torus.isPickable = false;
  83532. torus.parent = this._teleportationTarget;
  83533. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83534. var keys = [];
  83535. keys.push({
  83536. frame: 0,
  83537. value: 0
  83538. });
  83539. keys.push({
  83540. frame: 30,
  83541. value: 0.4
  83542. });
  83543. keys.push({
  83544. frame: 60,
  83545. value: 0
  83546. });
  83547. animationInnerCircle.setKeys(keys);
  83548. var easingFunction = new BABYLON.SineEase();
  83549. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83550. animationInnerCircle.setEasingFunction(easingFunction);
  83551. torus.animations = [];
  83552. torus.animations.push(animationInnerCircle);
  83553. this._scene.beginAnimation(torus, 0, 60, true);
  83554. this._hideTeleportationTarget();
  83555. };
  83556. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83557. this._teleportActive = true;
  83558. if (this._teleportationInitialized) {
  83559. this._teleportationTarget.isVisible = true;
  83560. if (this._isDefaultTeleportationTarget) {
  83561. this._teleportationTarget.getChildren()[0].isVisible = true;
  83562. }
  83563. }
  83564. };
  83565. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83566. this._teleportActive = false;
  83567. if (this._teleportationInitialized) {
  83568. this._teleportationTarget.isVisible = false;
  83569. if (this._isDefaultTeleportationTarget) {
  83570. this._teleportationTarget.getChildren()[0].isVisible = false;
  83571. }
  83572. }
  83573. };
  83574. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83575. var _this = this;
  83576. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83577. return;
  83578. }
  83579. if (right) {
  83580. this._rotationAngle++;
  83581. }
  83582. else {
  83583. this._rotationAngle--;
  83584. }
  83585. this.currentVRCamera.animations = [];
  83586. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83587. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83588. var animationRotationKeys = [];
  83589. animationRotationKeys.push({
  83590. frame: 0,
  83591. value: this.currentVRCamera.rotationQuaternion
  83592. });
  83593. animationRotationKeys.push({
  83594. frame: 6,
  83595. value: target
  83596. });
  83597. animationRotation.setKeys(animationRotationKeys);
  83598. animationRotation.setEasingFunction(this._circleEase);
  83599. this.currentVRCamera.animations.push(animationRotation);
  83600. this._postProcessMove.animations = [];
  83601. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83602. var vignetteWeightKeys = [];
  83603. vignetteWeightKeys.push({
  83604. frame: 0,
  83605. value: 0
  83606. });
  83607. vignetteWeightKeys.push({
  83608. frame: 3,
  83609. value: 4
  83610. });
  83611. vignetteWeightKeys.push({
  83612. frame: 6,
  83613. value: 0
  83614. });
  83615. animationPP.setKeys(vignetteWeightKeys);
  83616. animationPP.setEasingFunction(this._circleEase);
  83617. this._postProcessMove.animations.push(animationPP);
  83618. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83619. var vignetteStretchKeys = [];
  83620. vignetteStretchKeys.push({
  83621. frame: 0,
  83622. value: 0
  83623. });
  83624. vignetteStretchKeys.push({
  83625. frame: 3,
  83626. value: 10
  83627. });
  83628. vignetteStretchKeys.push({
  83629. frame: 6,
  83630. value: 0
  83631. });
  83632. animationPP2.setKeys(vignetteStretchKeys);
  83633. animationPP2.setEasingFunction(this._circleEase);
  83634. this._postProcessMove.animations.push(animationPP2);
  83635. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83636. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83637. this._postProcessMove.samples = 4;
  83638. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83639. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83640. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83641. });
  83642. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83643. };
  83644. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83645. if (hit.pickedPoint) {
  83646. if (gazer._teleportationRequestInitiated) {
  83647. this._displayTeleportationTarget();
  83648. this._haloCenter.copyFrom(hit.pickedPoint);
  83649. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83650. }
  83651. var pickNormal = hit.getNormal(true, false);
  83652. if (pickNormal) {
  83653. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83654. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83655. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83656. }
  83657. this._teleportationTarget.position.y += 0.1;
  83658. }
  83659. };
  83660. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83661. var _this = this;
  83662. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83663. return;
  83664. }
  83665. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83666. // offset of the headset from the anchor.
  83667. if (this.webVRCamera.leftCamera) {
  83668. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83669. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83670. location.subtractToRef(this._workingVector, this._workingVector);
  83671. }
  83672. else {
  83673. this._workingVector.copyFrom(location);
  83674. }
  83675. // Add height to account for user's height offset
  83676. if (this.isInVRMode) {
  83677. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83678. }
  83679. else {
  83680. this._workingVector.y += this._defaultHeight;
  83681. }
  83682. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83683. // Create animation from the camera's position to the new location
  83684. this.currentVRCamera.animations = [];
  83685. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83686. var animationCameraTeleportationKeys = [{
  83687. frame: 0,
  83688. value: this.currentVRCamera.position
  83689. },
  83690. {
  83691. frame: 11,
  83692. value: this._workingVector
  83693. }
  83694. ];
  83695. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83696. animationCameraTeleportation.setEasingFunction(this._circleEase);
  83697. this.currentVRCamera.animations.push(animationCameraTeleportation);
  83698. this._postProcessMove.animations = [];
  83699. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83700. var vignetteWeightKeys = [];
  83701. vignetteWeightKeys.push({
  83702. frame: 0,
  83703. value: 0
  83704. });
  83705. vignetteWeightKeys.push({
  83706. frame: 5,
  83707. value: 8
  83708. });
  83709. vignetteWeightKeys.push({
  83710. frame: 11,
  83711. value: 0
  83712. });
  83713. animationPP.setKeys(vignetteWeightKeys);
  83714. this._postProcessMove.animations.push(animationPP);
  83715. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83716. var vignetteStretchKeys = [];
  83717. vignetteStretchKeys.push({
  83718. frame: 0,
  83719. value: 0
  83720. });
  83721. vignetteStretchKeys.push({
  83722. frame: 5,
  83723. value: 10
  83724. });
  83725. vignetteStretchKeys.push({
  83726. frame: 11,
  83727. value: 0
  83728. });
  83729. animationPP2.setKeys(vignetteStretchKeys);
  83730. this._postProcessMove.animations.push(animationPP2);
  83731. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83732. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83733. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83734. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  83735. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83736. });
  83737. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  83738. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  83739. });
  83740. this._hideTeleportationTarget();
  83741. };
  83742. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  83743. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83744. return;
  83745. }
  83746. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  83747. // Moving the gazeTracker on the mesh face targetted
  83748. if (hit && hit.pickedPoint) {
  83749. if (this._displayGaze) {
  83750. var multiplier = 1;
  83751. gazer._gazeTracker.isVisible = true;
  83752. if (gazer._isActionableMesh) {
  83753. multiplier = 3;
  83754. }
  83755. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  83756. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  83757. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  83758. var pickNormal = hit.getNormal();
  83759. // To avoid z-fighting
  83760. var deltaFighting = 0.002;
  83761. if (pickNormal) {
  83762. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83763. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83764. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  83765. }
  83766. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  83767. if (gazer._gazeTracker.position.x < 0) {
  83768. gazer._gazeTracker.position.x += deltaFighting;
  83769. }
  83770. else {
  83771. gazer._gazeTracker.position.x -= deltaFighting;
  83772. }
  83773. if (gazer._gazeTracker.position.y < 0) {
  83774. gazer._gazeTracker.position.y += deltaFighting;
  83775. }
  83776. else {
  83777. gazer._gazeTracker.position.y -= deltaFighting;
  83778. }
  83779. if (gazer._gazeTracker.position.z < 0) {
  83780. gazer._gazeTracker.position.z += deltaFighting;
  83781. }
  83782. else {
  83783. gazer._gazeTracker.position.z -= deltaFighting;
  83784. }
  83785. }
  83786. // Changing the size of the laser pointer based on the distance from the targetted point
  83787. gazer._updatePointerDistance(hit.distance);
  83788. }
  83789. else {
  83790. gazer._gazeTracker.isVisible = false;
  83791. }
  83792. if (hit && hit.pickedMesh) {
  83793. gazer._currentHit = hit;
  83794. if (gazer._pointerDownOnMeshAsked) {
  83795. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83796. }
  83797. // The object selected is the floor, we're in a teleportation scenario
  83798. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83799. // Moving the teleportation area to this targetted point
  83800. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83801. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83802. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83803. }
  83804. gazer._currentMeshSelected = null;
  83805. if (gazer._teleportationRequestInitiated) {
  83806. this._moveTeleportationSelectorTo(hit, gazer);
  83807. }
  83808. return;
  83809. }
  83810. // If not, we're in a selection scenario
  83811. //this._teleportationAllowed = false;
  83812. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83813. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83814. this.onNewMeshPicked.notifyObservers(hit);
  83815. gazer._currentMeshSelected = hit.pickedMesh;
  83816. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83817. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83818. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83819. gazer._isActionableMesh = true;
  83820. }
  83821. else {
  83822. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83823. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83824. gazer._isActionableMesh = false;
  83825. }
  83826. try {
  83827. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83828. }
  83829. catch (err) {
  83830. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83831. }
  83832. }
  83833. else {
  83834. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83835. gazer._currentMeshSelected = null;
  83836. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83837. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83838. }
  83839. }
  83840. }
  83841. else {
  83842. gazer._currentHit = null;
  83843. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83844. gazer._currentMeshSelected = null;
  83845. //this._teleportationAllowed = false;
  83846. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83847. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83848. }
  83849. };
  83850. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83851. if (mesh) {
  83852. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83853. }
  83854. };
  83855. /**
  83856. * Sets the color of the laser ray from the vr controllers.
  83857. * @param color new color for the ray.
  83858. */
  83859. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83860. if (this.leftController) {
  83861. this.leftController._setLaserPointerColor(color);
  83862. }
  83863. if (this.rightController) {
  83864. this.rightController._setLaserPointerColor(color);
  83865. }
  83866. };
  83867. /**
  83868. * Sets the color of the ray from the vr headsets gaze.
  83869. * @param color new color for the ray.
  83870. */
  83871. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83872. if (!this._cameraGazer._gazeTracker.material) {
  83873. return;
  83874. }
  83875. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83876. if (this.leftController) {
  83877. this.leftController._gazeTracker.material.emissiveColor = color;
  83878. }
  83879. if (this.rightController) {
  83880. this.rightController._gazeTracker.material.emissiveColor = color;
  83881. }
  83882. };
  83883. /**
  83884. * Exits VR and disposes of the vr experience helper
  83885. */
  83886. VRExperienceHelper.prototype.dispose = function () {
  83887. if (this.isInVRMode) {
  83888. this.exitVR();
  83889. }
  83890. if (this._postProcessMove) {
  83891. this._postProcessMove.dispose();
  83892. }
  83893. if (this._webVRCamera) {
  83894. this._webVRCamera.dispose();
  83895. }
  83896. if (this._vrDeviceOrientationCamera) {
  83897. this._vrDeviceOrientationCamera.dispose();
  83898. }
  83899. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83900. document.body.removeChild(this._btnVR);
  83901. }
  83902. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83903. this._deviceOrientationCamera.dispose();
  83904. }
  83905. if (this._cameraGazer) {
  83906. this._cameraGazer.dispose();
  83907. }
  83908. if (this.leftController) {
  83909. this.leftController.dispose();
  83910. }
  83911. if (this.rightController) {
  83912. this.rightController.dispose();
  83913. }
  83914. if (this._teleportationTarget) {
  83915. this._teleportationTarget.dispose();
  83916. }
  83917. this._floorMeshesCollection = [];
  83918. document.removeEventListener("keydown", this._onKeyDown);
  83919. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83920. window.removeEventListener("resize", this._onResize);
  83921. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83922. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83923. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83924. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83925. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83926. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83927. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83928. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83929. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83930. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83931. this._scene.unregisterBeforeRender(this.beforeRender);
  83932. };
  83933. /**
  83934. * Gets the name of the VRExperienceHelper class
  83935. * @returns "VRExperienceHelper"
  83936. */
  83937. VRExperienceHelper.prototype.getClassName = function () {
  83938. return "VRExperienceHelper";
  83939. };
  83940. return VRExperienceHelper;
  83941. }());
  83942. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83943. })(BABYLON || (BABYLON = {}));
  83944. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83945. "use strict";
  83946. // Mainly based on these 2 articles :
  83947. // 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
  83948. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83949. var BABYLON;
  83950. (function (BABYLON) {
  83951. var JoystickAxis;
  83952. (function (JoystickAxis) {
  83953. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83954. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83955. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83956. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83957. var VirtualJoystick = /** @class */ (function () {
  83958. function VirtualJoystick(leftJoystick) {
  83959. var _this = this;
  83960. if (leftJoystick) {
  83961. this._leftJoystick = true;
  83962. }
  83963. else {
  83964. this._leftJoystick = false;
  83965. }
  83966. VirtualJoystick._globalJoystickIndex++;
  83967. // By default left & right arrow keys are moving the X
  83968. // and up & down keys are moving the Y
  83969. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83970. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83971. this.reverseLeftRight = false;
  83972. this.reverseUpDown = false;
  83973. // collections of pointers
  83974. this._touches = new BABYLON.StringDictionary();
  83975. this.deltaPosition = BABYLON.Vector3.Zero();
  83976. this._joystickSensibility = 25;
  83977. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83978. this._onResize = function (evt) {
  83979. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83980. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83981. if (VirtualJoystick.vjCanvas) {
  83982. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83983. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83984. }
  83985. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83986. };
  83987. // injecting a canvas element on top of the canvas 3D game
  83988. if (!VirtualJoystick.vjCanvas) {
  83989. window.addEventListener("resize", this._onResize, false);
  83990. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83991. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83992. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83993. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83994. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83995. VirtualJoystick.vjCanvas.style.width = "100%";
  83996. VirtualJoystick.vjCanvas.style.height = "100%";
  83997. VirtualJoystick.vjCanvas.style.position = "absolute";
  83998. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83999. VirtualJoystick.vjCanvas.style.top = "0px";
  84000. VirtualJoystick.vjCanvas.style.left = "0px";
  84001. VirtualJoystick.vjCanvas.style.zIndex = "5";
  84002. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  84003. // Support for jQuery PEP polyfill
  84004. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  84005. var context = VirtualJoystick.vjCanvas.getContext('2d');
  84006. if (!context) {
  84007. throw new Error("Unable to create canvas for virtual joystick");
  84008. }
  84009. VirtualJoystick.vjCanvasContext = context;
  84010. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  84011. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84012. document.body.appendChild(VirtualJoystick.vjCanvas);
  84013. }
  84014. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  84015. this.pressed = false;
  84016. // default joystick color
  84017. this._joystickColor = "cyan";
  84018. this._joystickPointerID = -1;
  84019. // current joystick position
  84020. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  84021. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  84022. // origin joystick position
  84023. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  84024. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  84025. this._onPointerDownHandlerRef = function (evt) {
  84026. _this._onPointerDown(evt);
  84027. };
  84028. this._onPointerMoveHandlerRef = function (evt) {
  84029. _this._onPointerMove(evt);
  84030. };
  84031. this._onPointerUpHandlerRef = function (evt) {
  84032. _this._onPointerUp(evt);
  84033. };
  84034. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  84035. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  84036. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84037. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84038. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84039. evt.preventDefault(); // Disables system menu
  84040. }, false);
  84041. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84042. }
  84043. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84044. this._joystickSensibility = newJoystickSensibility;
  84045. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84046. };
  84047. VirtualJoystick.prototype._onPointerDown = function (e) {
  84048. var positionOnScreenCondition;
  84049. e.preventDefault();
  84050. if (this._leftJoystick === true) {
  84051. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84052. }
  84053. else {
  84054. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84055. }
  84056. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84057. // First contact will be dedicated to the virtual joystick
  84058. this._joystickPointerID = e.pointerId;
  84059. this._joystickPointerStartPos.x = e.clientX;
  84060. this._joystickPointerStartPos.y = e.clientY;
  84061. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84062. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84063. this._deltaJoystickVector.x = 0;
  84064. this._deltaJoystickVector.y = 0;
  84065. this.pressed = true;
  84066. this._touches.add(e.pointerId.toString(), e);
  84067. }
  84068. else {
  84069. // You can only trigger the action buttons with a joystick declared
  84070. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84071. this._action();
  84072. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84073. }
  84074. }
  84075. };
  84076. VirtualJoystick.prototype._onPointerMove = function (e) {
  84077. // If the current pointer is the one associated to the joystick (first touch contact)
  84078. if (this._joystickPointerID == e.pointerId) {
  84079. this._joystickPointerPos.x = e.clientX;
  84080. this._joystickPointerPos.y = e.clientY;
  84081. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84082. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84083. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84084. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84085. switch (this._axisTargetedByLeftAndRight) {
  84086. case JoystickAxis.X:
  84087. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84088. break;
  84089. case JoystickAxis.Y:
  84090. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84091. break;
  84092. case JoystickAxis.Z:
  84093. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84094. break;
  84095. }
  84096. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84097. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84098. switch (this._axisTargetedByUpAndDown) {
  84099. case JoystickAxis.X:
  84100. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84101. break;
  84102. case JoystickAxis.Y:
  84103. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84104. break;
  84105. case JoystickAxis.Z:
  84106. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84107. break;
  84108. }
  84109. }
  84110. else {
  84111. var data = this._touches.get(e.pointerId.toString());
  84112. if (data) {
  84113. data.x = e.clientX;
  84114. data.y = e.clientY;
  84115. }
  84116. }
  84117. };
  84118. VirtualJoystick.prototype._onPointerUp = function (e) {
  84119. if (this._joystickPointerID == e.pointerId) {
  84120. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84121. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84122. this._joystickPointerID = -1;
  84123. this.pressed = false;
  84124. }
  84125. else {
  84126. var touch = this._touches.get(e.pointerId.toString());
  84127. if (touch) {
  84128. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84129. }
  84130. }
  84131. this._deltaJoystickVector.x = 0;
  84132. this._deltaJoystickVector.y = 0;
  84133. this._touches.remove(e.pointerId.toString());
  84134. };
  84135. /**
  84136. * Change the color of the virtual joystick
  84137. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84138. */
  84139. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84140. this._joystickColor = newColor;
  84141. };
  84142. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84143. this._action = action;
  84144. };
  84145. // Define which axis you'd like to control for left & right
  84146. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84147. switch (axis) {
  84148. case JoystickAxis.X:
  84149. case JoystickAxis.Y:
  84150. case JoystickAxis.Z:
  84151. this._axisTargetedByLeftAndRight = axis;
  84152. break;
  84153. default:
  84154. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84155. break;
  84156. }
  84157. };
  84158. // Define which axis you'd like to control for up & down
  84159. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84160. switch (axis) {
  84161. case JoystickAxis.X:
  84162. case JoystickAxis.Y:
  84163. case JoystickAxis.Z:
  84164. this._axisTargetedByUpAndDown = axis;
  84165. break;
  84166. default:
  84167. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84168. break;
  84169. }
  84170. };
  84171. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84172. var _this = this;
  84173. if (this.pressed) {
  84174. this._touches.forEach(function (key, touch) {
  84175. if (touch.pointerId === _this._joystickPointerID) {
  84176. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84177. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84178. VirtualJoystick.vjCanvasContext.beginPath();
  84179. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84180. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84181. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84182. VirtualJoystick.vjCanvasContext.stroke();
  84183. VirtualJoystick.vjCanvasContext.closePath();
  84184. VirtualJoystick.vjCanvasContext.beginPath();
  84185. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84186. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84187. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84188. VirtualJoystick.vjCanvasContext.stroke();
  84189. VirtualJoystick.vjCanvasContext.closePath();
  84190. VirtualJoystick.vjCanvasContext.beginPath();
  84191. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84192. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84193. VirtualJoystick.vjCanvasContext.stroke();
  84194. VirtualJoystick.vjCanvasContext.closePath();
  84195. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84196. }
  84197. else {
  84198. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84199. VirtualJoystick.vjCanvasContext.beginPath();
  84200. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84201. VirtualJoystick.vjCanvasContext.beginPath();
  84202. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84203. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84204. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84205. VirtualJoystick.vjCanvasContext.stroke();
  84206. VirtualJoystick.vjCanvasContext.closePath();
  84207. touch.prevX = touch.x;
  84208. touch.prevY = touch.y;
  84209. }
  84210. ;
  84211. });
  84212. }
  84213. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84214. };
  84215. VirtualJoystick.prototype.releaseCanvas = function () {
  84216. if (VirtualJoystick.vjCanvas) {
  84217. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84218. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84219. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84220. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84221. window.removeEventListener("resize", this._onResize);
  84222. document.body.removeChild(VirtualJoystick.vjCanvas);
  84223. VirtualJoystick.vjCanvas = null;
  84224. }
  84225. };
  84226. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84227. VirtualJoystick._globalJoystickIndex = 0;
  84228. return VirtualJoystick;
  84229. }());
  84230. BABYLON.VirtualJoystick = VirtualJoystick;
  84231. })(BABYLON || (BABYLON = {}));
  84232. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84233. "use strict";
  84234. var BABYLON;
  84235. (function (BABYLON) {
  84236. // We're mainly based on the logic defined into the FreeCamera code
  84237. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84238. __extends(VirtualJoysticksCamera, _super);
  84239. function VirtualJoysticksCamera(name, position, scene) {
  84240. var _this = _super.call(this, name, position, scene) || this;
  84241. _this.inputs.addVirtualJoystick();
  84242. return _this;
  84243. }
  84244. VirtualJoysticksCamera.prototype.getClassName = function () {
  84245. return "VirtualJoysticksCamera";
  84246. };
  84247. return VirtualJoysticksCamera;
  84248. }(BABYLON.FreeCamera));
  84249. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84250. })(BABYLON || (BABYLON = {}));
  84251. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84252. "use strict";
  84253. var BABYLON;
  84254. (function (BABYLON) {
  84255. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84256. function FreeCameraVirtualJoystickInput() {
  84257. }
  84258. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84259. return this._leftjoystick;
  84260. };
  84261. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84262. return this._rightjoystick;
  84263. };
  84264. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84265. if (this._leftjoystick) {
  84266. var camera = this.camera;
  84267. var speed = camera._computeLocalCameraSpeed() * 50;
  84268. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84269. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84270. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84271. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84272. if (!this._leftjoystick.pressed) {
  84273. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84274. }
  84275. if (!this._rightjoystick.pressed) {
  84276. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84277. }
  84278. }
  84279. };
  84280. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84281. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84282. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84283. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84284. this._leftjoystick.setJoystickSensibility(0.15);
  84285. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84286. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84287. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84288. this._rightjoystick.reverseUpDown = true;
  84289. this._rightjoystick.setJoystickSensibility(0.05);
  84290. this._rightjoystick.setJoystickColor("yellow");
  84291. };
  84292. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84293. this._leftjoystick.releaseCanvas();
  84294. this._rightjoystick.releaseCanvas();
  84295. };
  84296. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84297. return "FreeCameraVirtualJoystickInput";
  84298. };
  84299. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84300. return "virtualJoystick";
  84301. };
  84302. return FreeCameraVirtualJoystickInput;
  84303. }());
  84304. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84305. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84306. })(BABYLON || (BABYLON = {}));
  84307. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84308. "use strict";
  84309. var BABYLON;
  84310. (function (BABYLON) {
  84311. var SimplificationSettings = /** @class */ (function () {
  84312. function SimplificationSettings(quality, distance, optimizeMesh) {
  84313. this.quality = quality;
  84314. this.distance = distance;
  84315. this.optimizeMesh = optimizeMesh;
  84316. }
  84317. return SimplificationSettings;
  84318. }());
  84319. BABYLON.SimplificationSettings = SimplificationSettings;
  84320. var SimplificationQueue = /** @class */ (function () {
  84321. function SimplificationQueue() {
  84322. this.running = false;
  84323. this._simplificationArray = [];
  84324. }
  84325. SimplificationQueue.prototype.addTask = function (task) {
  84326. this._simplificationArray.push(task);
  84327. };
  84328. SimplificationQueue.prototype.executeNext = function () {
  84329. var task = this._simplificationArray.pop();
  84330. if (task) {
  84331. this.running = true;
  84332. this.runSimplification(task);
  84333. }
  84334. else {
  84335. this.running = false;
  84336. }
  84337. };
  84338. SimplificationQueue.prototype.runSimplification = function (task) {
  84339. var _this = this;
  84340. if (task.parallelProcessing) {
  84341. //parallel simplifier
  84342. task.settings.forEach(function (setting) {
  84343. var simplifier = _this.getSimplifier(task);
  84344. simplifier.simplify(setting, function (newMesh) {
  84345. task.mesh.addLODLevel(setting.distance, newMesh);
  84346. newMesh.isVisible = true;
  84347. //check if it is the last
  84348. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84349. //all done, run the success callback.
  84350. task.successCallback();
  84351. }
  84352. _this.executeNext();
  84353. });
  84354. });
  84355. }
  84356. else {
  84357. //single simplifier.
  84358. var simplifier = this.getSimplifier(task);
  84359. var runDecimation = function (setting, callback) {
  84360. simplifier.simplify(setting, function (newMesh) {
  84361. task.mesh.addLODLevel(setting.distance, newMesh);
  84362. newMesh.isVisible = true;
  84363. //run the next quality level
  84364. callback();
  84365. });
  84366. };
  84367. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84368. runDecimation(task.settings[loop.index], function () {
  84369. loop.executeNext();
  84370. });
  84371. }, function () {
  84372. //execution ended, run the success callback.
  84373. if (task.successCallback) {
  84374. task.successCallback();
  84375. }
  84376. _this.executeNext();
  84377. });
  84378. }
  84379. };
  84380. SimplificationQueue.prototype.getSimplifier = function (task) {
  84381. switch (task.simplificationType) {
  84382. case SimplificationType.QUADRATIC:
  84383. default:
  84384. return new QuadraticErrorSimplification(task.mesh);
  84385. }
  84386. };
  84387. return SimplificationQueue;
  84388. }());
  84389. BABYLON.SimplificationQueue = SimplificationQueue;
  84390. /**
  84391. * The implemented types of simplification.
  84392. * At the moment only Quadratic Error Decimation is implemented.
  84393. */
  84394. var SimplificationType;
  84395. (function (SimplificationType) {
  84396. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84397. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84398. var DecimationTriangle = /** @class */ (function () {
  84399. function DecimationTriangle(vertices) {
  84400. this.vertices = vertices;
  84401. this.error = new Array(4);
  84402. this.deleted = false;
  84403. this.isDirty = false;
  84404. this.deletePending = false;
  84405. this.borderFactor = 0;
  84406. }
  84407. return DecimationTriangle;
  84408. }());
  84409. BABYLON.DecimationTriangle = DecimationTriangle;
  84410. var DecimationVertex = /** @class */ (function () {
  84411. function DecimationVertex(position, id) {
  84412. this.position = position;
  84413. this.id = id;
  84414. this.isBorder = true;
  84415. this.q = new QuadraticMatrix();
  84416. this.triangleCount = 0;
  84417. this.triangleStart = 0;
  84418. this.originalOffsets = [];
  84419. }
  84420. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84421. this.position.copyFrom(newPosition);
  84422. };
  84423. return DecimationVertex;
  84424. }());
  84425. BABYLON.DecimationVertex = DecimationVertex;
  84426. var QuadraticMatrix = /** @class */ (function () {
  84427. function QuadraticMatrix(data) {
  84428. this.data = new Array(10);
  84429. for (var i = 0; i < 10; ++i) {
  84430. if (data && data[i]) {
  84431. this.data[i] = data[i];
  84432. }
  84433. else {
  84434. this.data[i] = 0;
  84435. }
  84436. }
  84437. }
  84438. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84439. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84440. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84441. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84442. return det;
  84443. };
  84444. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84445. for (var i = 0; i < 10; ++i) {
  84446. this.data[i] += matrix.data[i];
  84447. }
  84448. };
  84449. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84450. for (var i = 0; i < 10; ++i) {
  84451. this.data[i] += data[i];
  84452. }
  84453. };
  84454. QuadraticMatrix.prototype.add = function (matrix) {
  84455. var m = new QuadraticMatrix();
  84456. for (var i = 0; i < 10; ++i) {
  84457. m.data[i] = this.data[i] + matrix.data[i];
  84458. }
  84459. return m;
  84460. };
  84461. QuadraticMatrix.FromData = function (a, b, c, d) {
  84462. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84463. };
  84464. //returning an array to avoid garbage collection
  84465. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84466. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84467. };
  84468. return QuadraticMatrix;
  84469. }());
  84470. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84471. var Reference = /** @class */ (function () {
  84472. function Reference(vertexId, triangleId) {
  84473. this.vertexId = vertexId;
  84474. this.triangleId = triangleId;
  84475. }
  84476. return Reference;
  84477. }());
  84478. BABYLON.Reference = Reference;
  84479. /**
  84480. * An implementation of the Quadratic Error simplification algorithm.
  84481. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84482. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84483. * @author RaananW
  84484. */
  84485. var QuadraticErrorSimplification = /** @class */ (function () {
  84486. function QuadraticErrorSimplification(_mesh) {
  84487. this._mesh = _mesh;
  84488. this.syncIterations = 5000;
  84489. this.aggressiveness = 7;
  84490. this.decimationIterations = 100;
  84491. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84492. }
  84493. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84494. var _this = this;
  84495. this.initDecimatedMesh();
  84496. //iterating through the submeshes array, one after the other.
  84497. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84498. _this.initWithMesh(loop.index, function () {
  84499. _this.runDecimation(settings, loop.index, function () {
  84500. loop.executeNext();
  84501. });
  84502. }, settings.optimizeMesh);
  84503. }, function () {
  84504. setTimeout(function () {
  84505. successCallback(_this._reconstructedMesh);
  84506. }, 0);
  84507. });
  84508. };
  84509. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84510. var _this = this;
  84511. var targetCount = ~~(this.triangles.length * settings.quality);
  84512. var deletedTriangles = 0;
  84513. var triangleCount = this.triangles.length;
  84514. var iterationFunction = function (iteration, callback) {
  84515. setTimeout(function () {
  84516. if (iteration % 5 === 0) {
  84517. _this.updateMesh(iteration === 0);
  84518. }
  84519. for (var i = 0; i < _this.triangles.length; ++i) {
  84520. _this.triangles[i].isDirty = false;
  84521. }
  84522. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84523. var trianglesIterator = function (i) {
  84524. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84525. var t = _this.triangles[tIdx];
  84526. if (!t)
  84527. return;
  84528. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84529. return;
  84530. }
  84531. for (var j = 0; j < 3; ++j) {
  84532. if (t.error[j] < threshold) {
  84533. var deleted0 = [];
  84534. var deleted1 = [];
  84535. var v0 = t.vertices[j];
  84536. var v1 = t.vertices[(j + 1) % 3];
  84537. if (v0.isBorder || v1.isBorder)
  84538. continue;
  84539. var p = BABYLON.Vector3.Zero();
  84540. var n = BABYLON.Vector3.Zero();
  84541. var uv = BABYLON.Vector2.Zero();
  84542. var color = new BABYLON.Color4(0, 0, 0, 1);
  84543. _this.calculateError(v0, v1, p, n, uv, color);
  84544. var delTr = new Array();
  84545. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84546. continue;
  84547. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84548. continue;
  84549. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84550. continue;
  84551. var uniqueArray = new Array();
  84552. delTr.forEach(function (deletedT) {
  84553. if (uniqueArray.indexOf(deletedT) === -1) {
  84554. deletedT.deletePending = true;
  84555. uniqueArray.push(deletedT);
  84556. }
  84557. });
  84558. if (uniqueArray.length % 2 !== 0) {
  84559. continue;
  84560. }
  84561. v0.q = v1.q.add(v0.q);
  84562. v0.updatePosition(p);
  84563. var tStart = _this.references.length;
  84564. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84565. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84566. var tCount = _this.references.length - tStart;
  84567. if (tCount <= v0.triangleCount) {
  84568. if (tCount) {
  84569. for (var c = 0; c < tCount; c++) {
  84570. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84571. }
  84572. }
  84573. }
  84574. else {
  84575. v0.triangleStart = tStart;
  84576. }
  84577. v0.triangleCount = tCount;
  84578. break;
  84579. }
  84580. }
  84581. };
  84582. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84583. }, 0);
  84584. };
  84585. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84586. if (triangleCount - deletedTriangles <= targetCount)
  84587. loop.breakLoop();
  84588. else {
  84589. iterationFunction(loop.index, function () {
  84590. loop.executeNext();
  84591. });
  84592. }
  84593. }, function () {
  84594. setTimeout(function () {
  84595. //reconstruct this part of the mesh
  84596. _this.reconstructMesh(submeshIndex);
  84597. successCallback();
  84598. }, 0);
  84599. });
  84600. };
  84601. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84602. var _this = this;
  84603. this.vertices = [];
  84604. this.triangles = [];
  84605. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84606. var indices = this._mesh.getIndices();
  84607. var submesh = this._mesh.subMeshes[submeshIndex];
  84608. var findInVertices = function (positionToSearch) {
  84609. if (optimizeMesh) {
  84610. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84611. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84612. return _this.vertices[ii];
  84613. }
  84614. }
  84615. }
  84616. return null;
  84617. };
  84618. var vertexReferences = [];
  84619. var vertexInit = function (i) {
  84620. if (!positionData) {
  84621. return;
  84622. }
  84623. var offset = i + submesh.verticesStart;
  84624. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84625. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84626. vertex.originalOffsets.push(offset);
  84627. if (vertex.id === _this.vertices.length) {
  84628. _this.vertices.push(vertex);
  84629. }
  84630. vertexReferences.push(vertex.id);
  84631. };
  84632. //var totalVertices = mesh.getTotalVertices();
  84633. var totalVertices = submesh.verticesCount;
  84634. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84635. var indicesInit = function (i) {
  84636. if (!indices) {
  84637. return;
  84638. }
  84639. var offset = (submesh.indexStart / 3) + i;
  84640. var pos = (offset * 3);
  84641. var i0 = indices[pos + 0];
  84642. var i1 = indices[pos + 1];
  84643. var i2 = indices[pos + 2];
  84644. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84645. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84646. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84647. var triangle = new DecimationTriangle([v0, v1, v2]);
  84648. triangle.originalOffset = pos;
  84649. _this.triangles.push(triangle);
  84650. };
  84651. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84652. _this.init(callback);
  84653. });
  84654. });
  84655. };
  84656. QuadraticErrorSimplification.prototype.init = function (callback) {
  84657. var _this = this;
  84658. var triangleInit1 = function (i) {
  84659. var t = _this.triangles[i];
  84660. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84661. for (var j = 0; j < 3; j++) {
  84662. 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))));
  84663. }
  84664. };
  84665. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84666. var triangleInit2 = function (i) {
  84667. var t = _this.triangles[i];
  84668. for (var j = 0; j < 3; ++j) {
  84669. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84670. }
  84671. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84672. };
  84673. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84674. callback();
  84675. });
  84676. });
  84677. };
  84678. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84679. var newTriangles = [];
  84680. var i;
  84681. for (i = 0; i < this.vertices.length; ++i) {
  84682. this.vertices[i].triangleCount = 0;
  84683. }
  84684. var t;
  84685. var j;
  84686. for (i = 0; i < this.triangles.length; ++i) {
  84687. if (!this.triangles[i].deleted) {
  84688. t = this.triangles[i];
  84689. for (j = 0; j < 3; ++j) {
  84690. t.vertices[j].triangleCount = 1;
  84691. }
  84692. newTriangles.push(t);
  84693. }
  84694. }
  84695. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84696. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  84697. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  84698. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  84699. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  84700. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84701. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  84702. var vertexCount = 0;
  84703. for (i = 0; i < this.vertices.length; ++i) {
  84704. var vertex = this.vertices[i];
  84705. vertex.id = vertexCount;
  84706. if (vertex.triangleCount) {
  84707. vertex.originalOffsets.forEach(function (originalOffset) {
  84708. if (!normalData) {
  84709. return;
  84710. }
  84711. newPositionData.push(vertex.position.x);
  84712. newPositionData.push(vertex.position.y);
  84713. newPositionData.push(vertex.position.z);
  84714. newNormalData.push(normalData[originalOffset * 3]);
  84715. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84716. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84717. if (uvs && uvs.length) {
  84718. newUVsData.push(uvs[(originalOffset * 2)]);
  84719. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  84720. }
  84721. else if (colorsData && colorsData.length) {
  84722. newColorsData.push(colorsData[(originalOffset * 4)]);
  84723. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  84724. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  84725. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  84726. }
  84727. ++vertexCount;
  84728. });
  84729. }
  84730. }
  84731. var startingIndex = this._reconstructedMesh.getTotalIndices();
  84732. var startingVertex = this._reconstructedMesh.getTotalVertices();
  84733. var submeshesArray = this._reconstructedMesh.subMeshes;
  84734. this._reconstructedMesh.subMeshes = [];
  84735. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  84736. var originalIndices = this._mesh.getIndices();
  84737. for (i = 0; i < newTriangles.length; ++i) {
  84738. t = newTriangles[i]; //now get the new referencing point for each vertex
  84739. [0, 1, 2].forEach(function (idx) {
  84740. var id = originalIndices[t.originalOffset + idx];
  84741. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  84742. if (offset < 0)
  84743. offset = 0;
  84744. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  84745. });
  84746. }
  84747. //overwriting the old vertex buffers and indices.
  84748. this._reconstructedMesh.setIndices(newIndicesArray);
  84749. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  84750. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  84751. if (newUVsData.length > 0)
  84752. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  84753. if (newColorsData.length > 0)
  84754. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  84755. //create submesh
  84756. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  84757. if (submeshIndex > 0) {
  84758. this._reconstructedMesh.subMeshes = [];
  84759. submeshesArray.forEach(function (submesh) {
  84760. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  84761. });
  84762. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  84763. }
  84764. };
  84765. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  84766. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  84767. this._reconstructedMesh.material = this._mesh.material;
  84768. this._reconstructedMesh.parent = this._mesh.parent;
  84769. this._reconstructedMesh.isVisible = false;
  84770. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  84771. };
  84772. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  84773. for (var i = 0; i < vertex1.triangleCount; ++i) {
  84774. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  84775. if (t.deleted)
  84776. continue;
  84777. var s = this.references[vertex1.triangleStart + i].vertexId;
  84778. var v1 = t.vertices[(s + 1) % 3];
  84779. var v2 = t.vertices[(s + 2) % 3];
  84780. if ((v1 === vertex2 || v2 === vertex2)) {
  84781. deletedArray[i] = true;
  84782. delTr.push(t);
  84783. continue;
  84784. }
  84785. var d1 = v1.position.subtract(point);
  84786. d1 = d1.normalize();
  84787. var d2 = v2.position.subtract(point);
  84788. d2 = d2.normalize();
  84789. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84790. return true;
  84791. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84792. deletedArray[i] = false;
  84793. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84794. return true;
  84795. }
  84796. return false;
  84797. };
  84798. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84799. var newDeleted = deletedTriangles;
  84800. for (var i = 0; i < vertex.triangleCount; ++i) {
  84801. var ref = this.references[vertex.triangleStart + i];
  84802. var t = this.triangles[ref.triangleId];
  84803. if (t.deleted)
  84804. continue;
  84805. if (deletedArray[i] && t.deletePending) {
  84806. t.deleted = true;
  84807. newDeleted++;
  84808. continue;
  84809. }
  84810. t.vertices[ref.vertexId] = origVertex;
  84811. t.isDirty = true;
  84812. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84813. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84814. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84815. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84816. this.references.push(ref);
  84817. }
  84818. return newDeleted;
  84819. };
  84820. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84821. for (var i = 0; i < this.vertices.length; ++i) {
  84822. var vCount = [];
  84823. var vId = [];
  84824. var v = this.vertices[i];
  84825. var j;
  84826. for (j = 0; j < v.triangleCount; ++j) {
  84827. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84828. for (var ii = 0; ii < 3; ii++) {
  84829. var ofs = 0;
  84830. var vv = triangle.vertices[ii];
  84831. while (ofs < vCount.length) {
  84832. if (vId[ofs] === vv.id)
  84833. break;
  84834. ++ofs;
  84835. }
  84836. if (ofs === vCount.length) {
  84837. vCount.push(1);
  84838. vId.push(vv.id);
  84839. }
  84840. else {
  84841. vCount[ofs]++;
  84842. }
  84843. }
  84844. }
  84845. for (j = 0; j < vCount.length; ++j) {
  84846. if (vCount[j] === 1) {
  84847. this.vertices[vId[j]].isBorder = true;
  84848. }
  84849. else {
  84850. this.vertices[vId[j]].isBorder = false;
  84851. }
  84852. }
  84853. }
  84854. };
  84855. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84856. if (identifyBorders === void 0) { identifyBorders = false; }
  84857. var i;
  84858. if (!identifyBorders) {
  84859. var newTrianglesVector = [];
  84860. for (i = 0; i < this.triangles.length; ++i) {
  84861. if (!this.triangles[i].deleted) {
  84862. newTrianglesVector.push(this.triangles[i]);
  84863. }
  84864. }
  84865. this.triangles = newTrianglesVector;
  84866. }
  84867. for (i = 0; i < this.vertices.length; ++i) {
  84868. this.vertices[i].triangleCount = 0;
  84869. this.vertices[i].triangleStart = 0;
  84870. }
  84871. var t;
  84872. var j;
  84873. var v;
  84874. for (i = 0; i < this.triangles.length; ++i) {
  84875. t = this.triangles[i];
  84876. for (j = 0; j < 3; ++j) {
  84877. v = t.vertices[j];
  84878. v.triangleCount++;
  84879. }
  84880. }
  84881. var tStart = 0;
  84882. for (i = 0; i < this.vertices.length; ++i) {
  84883. this.vertices[i].triangleStart = tStart;
  84884. tStart += this.vertices[i].triangleCount;
  84885. this.vertices[i].triangleCount = 0;
  84886. }
  84887. var newReferences = new Array(this.triangles.length * 3);
  84888. for (i = 0; i < this.triangles.length; ++i) {
  84889. t = this.triangles[i];
  84890. for (j = 0; j < 3; ++j) {
  84891. v = t.vertices[j];
  84892. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84893. v.triangleCount++;
  84894. }
  84895. }
  84896. this.references = newReferences;
  84897. if (identifyBorders) {
  84898. this.identifyBorder();
  84899. }
  84900. };
  84901. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84902. var x = point.x;
  84903. var y = point.y;
  84904. var z = point.z;
  84905. 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
  84906. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84907. };
  84908. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84909. var q = vertex1.q.add(vertex2.q);
  84910. var border = vertex1.isBorder && vertex2.isBorder;
  84911. var error = 0;
  84912. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84913. if (qDet !== 0 && !border) {
  84914. if (!pointResult) {
  84915. pointResult = BABYLON.Vector3.Zero();
  84916. }
  84917. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84918. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84919. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84920. error = this.vertexError(q, pointResult);
  84921. }
  84922. else {
  84923. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84924. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84925. var error1 = this.vertexError(q, vertex1.position);
  84926. var error2 = this.vertexError(q, vertex2.position);
  84927. var error3 = this.vertexError(q, p3);
  84928. error = Math.min(error1, error2, error3);
  84929. if (error === error1) {
  84930. if (pointResult) {
  84931. pointResult.copyFrom(vertex1.position);
  84932. }
  84933. }
  84934. else if (error === error2) {
  84935. if (pointResult) {
  84936. pointResult.copyFrom(vertex2.position);
  84937. }
  84938. }
  84939. else {
  84940. if (pointResult) {
  84941. pointResult.copyFrom(p3);
  84942. }
  84943. }
  84944. }
  84945. return error;
  84946. };
  84947. return QuadraticErrorSimplification;
  84948. }());
  84949. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84950. })(BABYLON || (BABYLON = {}));
  84951. //# sourceMappingURL=babylon.meshSimplification.js.map
  84952. "use strict";
  84953. var BABYLON;
  84954. (function (BABYLON) {
  84955. var MeshLODLevel = /** @class */ (function () {
  84956. function MeshLODLevel(distance, mesh) {
  84957. this.distance = distance;
  84958. this.mesh = mesh;
  84959. }
  84960. return MeshLODLevel;
  84961. }());
  84962. BABYLON.MeshLODLevel = MeshLODLevel;
  84963. })(BABYLON || (BABYLON = {}));
  84964. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84965. "use strict";
  84966. var BABYLON;
  84967. (function (BABYLON) {
  84968. /**
  84969. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84970. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84971. */
  84972. var SceneOptimization = /** @class */ (function () {
  84973. /**
  84974. * Creates the SceneOptimization object
  84975. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84976. * @param desc defines the description associated with the optimization
  84977. */
  84978. function SceneOptimization(
  84979. /**
  84980. * Defines the priority of this optimization (0 by default which means first in the list)
  84981. */
  84982. priority) {
  84983. if (priority === void 0) { priority = 0; }
  84984. this.priority = priority;
  84985. }
  84986. /**
  84987. * Gets a string describing the action executed by the current optimization
  84988. * @returns description string
  84989. */
  84990. SceneOptimization.prototype.getDescription = function () {
  84991. return "";
  84992. };
  84993. /**
  84994. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84995. * @param scene defines the current scene where to apply this optimization
  84996. * @param optimizer defines the current optimizer
  84997. * @returns true if everything that can be done was applied
  84998. */
  84999. SceneOptimization.prototype.apply = function (scene, optimizer) {
  85000. return true;
  85001. };
  85002. ;
  85003. return SceneOptimization;
  85004. }());
  85005. BABYLON.SceneOptimization = SceneOptimization;
  85006. /**
  85007. * Defines an optimization used to reduce the size of render target textures
  85008. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85009. */
  85010. var TextureOptimization = /** @class */ (function (_super) {
  85011. __extends(TextureOptimization, _super);
  85012. /**
  85013. * Creates the TextureOptimization object
  85014. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85015. * @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
  85016. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85017. */
  85018. function TextureOptimization(
  85019. /**
  85020. * Defines the priority of this optimization (0 by default which means first in the list)
  85021. */
  85022. priority,
  85023. /**
  85024. * 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
  85025. */
  85026. maximumSize,
  85027. /**
  85028. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85029. */
  85030. step) {
  85031. if (priority === void 0) { priority = 0; }
  85032. if (maximumSize === void 0) { maximumSize = 1024; }
  85033. if (step === void 0) { step = 0.5; }
  85034. var _this = _super.call(this, priority) || this;
  85035. _this.priority = priority;
  85036. _this.maximumSize = maximumSize;
  85037. _this.step = step;
  85038. return _this;
  85039. }
  85040. /**
  85041. * Gets a string describing the action executed by the current optimization
  85042. * @returns description string
  85043. */
  85044. TextureOptimization.prototype.getDescription = function () {
  85045. return "Reducing render target texture size to " + this.maximumSize;
  85046. };
  85047. /**
  85048. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85049. * @param scene defines the current scene where to apply this optimization
  85050. * @param optimizer defines the current optimizer
  85051. * @returns true if everything that can be done was applied
  85052. */
  85053. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85054. var allDone = true;
  85055. for (var index = 0; index < scene.textures.length; index++) {
  85056. var texture = scene.textures[index];
  85057. if (!texture.canRescale || texture.getContext) {
  85058. continue;
  85059. }
  85060. var currentSize = texture.getSize();
  85061. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85062. if (maxDimension > this.maximumSize) {
  85063. texture.scale(this.step);
  85064. allDone = false;
  85065. }
  85066. }
  85067. return allDone;
  85068. };
  85069. return TextureOptimization;
  85070. }(SceneOptimization));
  85071. BABYLON.TextureOptimization = TextureOptimization;
  85072. /**
  85073. * Defines an optimization used to increase or decrease the rendering resolution
  85074. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85075. */
  85076. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85077. __extends(HardwareScalingOptimization, _super);
  85078. /**
  85079. * Creates the HardwareScalingOptimization object
  85080. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85081. * @param maximumScale defines the maximum scale to use (2 by default)
  85082. * @param step defines the step to use between two passes (0.5 by default)
  85083. */
  85084. function HardwareScalingOptimization(
  85085. /**
  85086. * Defines the priority of this optimization (0 by default which means first in the list)
  85087. */
  85088. priority,
  85089. /**
  85090. * Defines the maximum scale to use (2 by default)
  85091. */
  85092. maximumScale,
  85093. /**
  85094. * Defines the step to use between two passes (0.5 by default)
  85095. */
  85096. step) {
  85097. if (priority === void 0) { priority = 0; }
  85098. if (maximumScale === void 0) { maximumScale = 2; }
  85099. if (step === void 0) { step = 0.25; }
  85100. var _this = _super.call(this, priority) || this;
  85101. _this.priority = priority;
  85102. _this.maximumScale = maximumScale;
  85103. _this.step = step;
  85104. _this._currentScale = -1;
  85105. _this._directionOffset = 1;
  85106. return _this;
  85107. }
  85108. /**
  85109. * Gets a string describing the action executed by the current optimization
  85110. * @return description string
  85111. */
  85112. HardwareScalingOptimization.prototype.getDescription = function () {
  85113. return "Setting hardware scaling level to " + this._currentScale;
  85114. };
  85115. /**
  85116. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85117. * @param scene defines the current scene where to apply this optimization
  85118. * @param optimizer defines the current optimizer
  85119. * @returns true if everything that can be done was applied
  85120. */
  85121. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85122. if (this._currentScale === -1) {
  85123. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85124. if (this._currentScale > this.maximumScale) {
  85125. this._directionOffset = -1;
  85126. }
  85127. }
  85128. this._currentScale += this._directionOffset * this.step;
  85129. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85130. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85131. };
  85132. ;
  85133. return HardwareScalingOptimization;
  85134. }(SceneOptimization));
  85135. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85136. /**
  85137. * Defines an optimization used to remove shadows
  85138. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85139. */
  85140. var ShadowsOptimization = /** @class */ (function (_super) {
  85141. __extends(ShadowsOptimization, _super);
  85142. function ShadowsOptimization() {
  85143. return _super !== null && _super.apply(this, arguments) || this;
  85144. }
  85145. /**
  85146. * Gets a string describing the action executed by the current optimization
  85147. * @return description string
  85148. */
  85149. ShadowsOptimization.prototype.getDescription = function () {
  85150. return "Turning shadows on/off";
  85151. };
  85152. /**
  85153. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85154. * @param scene defines the current scene where to apply this optimization
  85155. * @param optimizer defines the current optimizer
  85156. * @returns true if everything that can be done was applied
  85157. */
  85158. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85159. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85160. return true;
  85161. };
  85162. ;
  85163. return ShadowsOptimization;
  85164. }(SceneOptimization));
  85165. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85166. /**
  85167. * Defines an optimization used to turn post-processes off
  85168. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85169. */
  85170. var PostProcessesOptimization = /** @class */ (function (_super) {
  85171. __extends(PostProcessesOptimization, _super);
  85172. function PostProcessesOptimization() {
  85173. return _super !== null && _super.apply(this, arguments) || this;
  85174. }
  85175. /**
  85176. * Gets a string describing the action executed by the current optimization
  85177. * @return description string
  85178. */
  85179. PostProcessesOptimization.prototype.getDescription = function () {
  85180. return "Turning post-processes on/off";
  85181. };
  85182. /**
  85183. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85184. * @param scene defines the current scene where to apply this optimization
  85185. * @param optimizer defines the current optimizer
  85186. * @returns true if everything that can be done was applied
  85187. */
  85188. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85189. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85190. return true;
  85191. };
  85192. ;
  85193. return PostProcessesOptimization;
  85194. }(SceneOptimization));
  85195. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85196. /**
  85197. * Defines an optimization used to turn lens flares off
  85198. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85199. */
  85200. var LensFlaresOptimization = /** @class */ (function (_super) {
  85201. __extends(LensFlaresOptimization, _super);
  85202. function LensFlaresOptimization() {
  85203. return _super !== null && _super.apply(this, arguments) || this;
  85204. }
  85205. /**
  85206. * Gets a string describing the action executed by the current optimization
  85207. * @return description string
  85208. */
  85209. LensFlaresOptimization.prototype.getDescription = function () {
  85210. return "Turning lens flares on/off";
  85211. };
  85212. /**
  85213. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85214. * @param scene defines the current scene where to apply this optimization
  85215. * @param optimizer defines the current optimizer
  85216. * @returns true if everything that can be done was applied
  85217. */
  85218. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85219. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85220. return true;
  85221. };
  85222. ;
  85223. return LensFlaresOptimization;
  85224. }(SceneOptimization));
  85225. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85226. /**
  85227. * Defines an optimization based on user defined callback.
  85228. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85229. */
  85230. var CustomOptimization = /** @class */ (function (_super) {
  85231. __extends(CustomOptimization, _super);
  85232. function CustomOptimization() {
  85233. return _super !== null && _super.apply(this, arguments) || this;
  85234. }
  85235. /**
  85236. * Gets a string describing the action executed by the current optimization
  85237. * @returns description string
  85238. */
  85239. CustomOptimization.prototype.getDescription = function () {
  85240. if (this.onGetDescription) {
  85241. return this.onGetDescription();
  85242. }
  85243. return "Running user defined callback";
  85244. };
  85245. /**
  85246. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85247. * @param scene defines the current scene where to apply this optimization
  85248. * @param optimizer defines the current optimizer
  85249. * @returns true if everything that can be done was applied
  85250. */
  85251. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85252. if (this.onApply) {
  85253. return this.onApply(scene, optimizer);
  85254. }
  85255. return true;
  85256. };
  85257. ;
  85258. return CustomOptimization;
  85259. }(SceneOptimization));
  85260. BABYLON.CustomOptimization = CustomOptimization;
  85261. /**
  85262. * Defines an optimization used to turn particles off
  85263. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85264. */
  85265. var ParticlesOptimization = /** @class */ (function (_super) {
  85266. __extends(ParticlesOptimization, _super);
  85267. function ParticlesOptimization() {
  85268. return _super !== null && _super.apply(this, arguments) || this;
  85269. }
  85270. /**
  85271. * Gets a string describing the action executed by the current optimization
  85272. * @return description string
  85273. */
  85274. ParticlesOptimization.prototype.getDescription = function () {
  85275. return "Turning particles on/off";
  85276. };
  85277. /**
  85278. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85279. * @param scene defines the current scene where to apply this optimization
  85280. * @param optimizer defines the current optimizer
  85281. * @returns true if everything that can be done was applied
  85282. */
  85283. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85284. scene.particlesEnabled = optimizer.isInImprovementMode;
  85285. return true;
  85286. };
  85287. ;
  85288. return ParticlesOptimization;
  85289. }(SceneOptimization));
  85290. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85291. /**
  85292. * Defines an optimization used to turn render targets off
  85293. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85294. */
  85295. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85296. __extends(RenderTargetsOptimization, _super);
  85297. function RenderTargetsOptimization() {
  85298. return _super !== null && _super.apply(this, arguments) || this;
  85299. }
  85300. /**
  85301. * Gets a string describing the action executed by the current optimization
  85302. * @return description string
  85303. */
  85304. RenderTargetsOptimization.prototype.getDescription = function () {
  85305. return "Turning render targets off";
  85306. };
  85307. /**
  85308. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85309. * @param scene defines the current scene where to apply this optimization
  85310. * @param optimizer defines the current optimizer
  85311. * @returns true if everything that can be done was applied
  85312. */
  85313. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85314. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85315. return true;
  85316. };
  85317. ;
  85318. return RenderTargetsOptimization;
  85319. }(SceneOptimization));
  85320. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85321. /**
  85322. * Defines an optimization used to merge meshes with compatible materials
  85323. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85324. */
  85325. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85326. __extends(MergeMeshesOptimization, _super);
  85327. function MergeMeshesOptimization() {
  85328. var _this = _super !== null && _super.apply(this, arguments) || this;
  85329. _this._canBeMerged = function (abstractMesh) {
  85330. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85331. return false;
  85332. }
  85333. var mesh = abstractMesh;
  85334. if (!mesh.isVisible || !mesh.isEnabled()) {
  85335. return false;
  85336. }
  85337. if (mesh.instances.length > 0) {
  85338. return false;
  85339. }
  85340. if (mesh.skeleton || mesh.hasLODLevels) {
  85341. return false;
  85342. }
  85343. if (mesh.parent) {
  85344. return false;
  85345. }
  85346. return true;
  85347. };
  85348. return _this;
  85349. }
  85350. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85351. /**
  85352. * Gets or sets a boolean which defines if optimization octree has to be updated
  85353. */
  85354. get: function () {
  85355. return MergeMeshesOptimization._UpdateSelectionTree;
  85356. },
  85357. /**
  85358. * Gets or sets a boolean which defines if optimization octree has to be updated
  85359. */
  85360. set: function (value) {
  85361. MergeMeshesOptimization._UpdateSelectionTree = value;
  85362. },
  85363. enumerable: true,
  85364. configurable: true
  85365. });
  85366. /**
  85367. * Gets a string describing the action executed by the current optimization
  85368. * @return description string
  85369. */
  85370. MergeMeshesOptimization.prototype.getDescription = function () {
  85371. return "Merging similar meshes together";
  85372. };
  85373. /**
  85374. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85375. * @param scene defines the current scene where to apply this optimization
  85376. * @param optimizer defines the current optimizer
  85377. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85378. * @returns true if everything that can be done was applied
  85379. */
  85380. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85381. var globalPool = scene.meshes.slice(0);
  85382. var globalLength = globalPool.length;
  85383. for (var index = 0; index < globalLength; index++) {
  85384. var currentPool = new Array();
  85385. var current = globalPool[index];
  85386. // Checks
  85387. if (!this._canBeMerged(current)) {
  85388. continue;
  85389. }
  85390. currentPool.push(current);
  85391. // Find compatible meshes
  85392. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85393. var otherMesh = globalPool[subIndex];
  85394. if (!this._canBeMerged(otherMesh)) {
  85395. continue;
  85396. }
  85397. if (otherMesh.material !== current.material) {
  85398. continue;
  85399. }
  85400. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85401. continue;
  85402. }
  85403. currentPool.push(otherMesh);
  85404. globalLength--;
  85405. globalPool.splice(subIndex, 1);
  85406. subIndex--;
  85407. }
  85408. if (currentPool.length < 2) {
  85409. continue;
  85410. }
  85411. // Merge meshes
  85412. BABYLON.Mesh.MergeMeshes(currentPool);
  85413. }
  85414. if (updateSelectionTree != undefined) {
  85415. if (updateSelectionTree) {
  85416. scene.createOrUpdateSelectionOctree();
  85417. }
  85418. }
  85419. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85420. scene.createOrUpdateSelectionOctree();
  85421. }
  85422. return true;
  85423. };
  85424. ;
  85425. MergeMeshesOptimization._UpdateSelectionTree = false;
  85426. return MergeMeshesOptimization;
  85427. }(SceneOptimization));
  85428. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85429. /**
  85430. * Defines a list of options used by SceneOptimizer
  85431. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85432. */
  85433. var SceneOptimizerOptions = /** @class */ (function () {
  85434. /**
  85435. * Creates a new list of options used by SceneOptimizer
  85436. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85437. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85438. */
  85439. function SceneOptimizerOptions(
  85440. /**
  85441. * Defines the target frame rate to reach (60 by default)
  85442. */
  85443. targetFrameRate,
  85444. /**
  85445. * Defines the interval between two checkes (2000ms by default)
  85446. */
  85447. trackerDuration) {
  85448. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85449. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85450. this.targetFrameRate = targetFrameRate;
  85451. this.trackerDuration = trackerDuration;
  85452. /**
  85453. * Gets the list of optimizations to apply
  85454. */
  85455. this.optimizations = new Array();
  85456. }
  85457. /**
  85458. * Add a new optimization
  85459. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85460. * @returns the current SceneOptimizerOptions
  85461. */
  85462. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85463. this.optimizations.push(optimization);
  85464. return this;
  85465. };
  85466. /**
  85467. * Add a new custom optimization
  85468. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85469. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85470. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85471. * @returns the current SceneOptimizerOptions
  85472. */
  85473. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85474. if (priority === void 0) { priority = 0; }
  85475. var optimization = new CustomOptimization(priority);
  85476. optimization.onApply = onApply;
  85477. optimization.onGetDescription = onGetDescription;
  85478. this.optimizations.push(optimization);
  85479. return this;
  85480. };
  85481. /**
  85482. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85483. * @param targetFrameRate defines the target frame rate (60 by default)
  85484. * @returns a SceneOptimizerOptions object
  85485. */
  85486. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85487. var result = new SceneOptimizerOptions(targetFrameRate);
  85488. var priority = 0;
  85489. result.addOptimization(new MergeMeshesOptimization(priority));
  85490. result.addOptimization(new ShadowsOptimization(priority));
  85491. result.addOptimization(new LensFlaresOptimization(priority));
  85492. // Next priority
  85493. priority++;
  85494. result.addOptimization(new PostProcessesOptimization(priority));
  85495. result.addOptimization(new ParticlesOptimization(priority));
  85496. // Next priority
  85497. priority++;
  85498. result.addOptimization(new TextureOptimization(priority, 1024));
  85499. return result;
  85500. };
  85501. /**
  85502. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85503. * @param targetFrameRate defines the target frame rate (60 by default)
  85504. * @returns a SceneOptimizerOptions object
  85505. */
  85506. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85507. var result = new SceneOptimizerOptions(targetFrameRate);
  85508. var priority = 0;
  85509. result.addOptimization(new MergeMeshesOptimization(priority));
  85510. result.addOptimization(new ShadowsOptimization(priority));
  85511. result.addOptimization(new LensFlaresOptimization(priority));
  85512. // Next priority
  85513. priority++;
  85514. result.addOptimization(new PostProcessesOptimization(priority));
  85515. result.addOptimization(new ParticlesOptimization(priority));
  85516. // Next priority
  85517. priority++;
  85518. result.addOptimization(new TextureOptimization(priority, 512));
  85519. // Next priority
  85520. priority++;
  85521. result.addOptimization(new RenderTargetsOptimization(priority));
  85522. // Next priority
  85523. priority++;
  85524. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85525. return result;
  85526. };
  85527. /**
  85528. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85529. * @param targetFrameRate defines the target frame rate (60 by default)
  85530. * @returns a SceneOptimizerOptions object
  85531. */
  85532. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85533. var result = new SceneOptimizerOptions(targetFrameRate);
  85534. var priority = 0;
  85535. result.addOptimization(new MergeMeshesOptimization(priority));
  85536. result.addOptimization(new ShadowsOptimization(priority));
  85537. result.addOptimization(new LensFlaresOptimization(priority));
  85538. // Next priority
  85539. priority++;
  85540. result.addOptimization(new PostProcessesOptimization(priority));
  85541. result.addOptimization(new ParticlesOptimization(priority));
  85542. // Next priority
  85543. priority++;
  85544. result.addOptimization(new TextureOptimization(priority, 256));
  85545. // Next priority
  85546. priority++;
  85547. result.addOptimization(new RenderTargetsOptimization(priority));
  85548. // Next priority
  85549. priority++;
  85550. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85551. return result;
  85552. };
  85553. return SceneOptimizerOptions;
  85554. }());
  85555. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85556. /**
  85557. * Class used to run optimizations in order to reach a target frame rate
  85558. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85559. */
  85560. var SceneOptimizer = /** @class */ (function () {
  85561. /**
  85562. * Creates a new SceneOptimizer
  85563. * @param scene defines the scene to work on
  85564. * @param options defines the options to use with the SceneOptimizer
  85565. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85566. * @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)
  85567. */
  85568. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85569. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85570. if (improvementMode === void 0) { improvementMode = false; }
  85571. var _this = this;
  85572. this._isRunning = false;
  85573. this._currentPriorityLevel = 0;
  85574. this._targetFrameRate = 60;
  85575. this._trackerDuration = 2000;
  85576. this._currentFrameRate = 0;
  85577. this._improvementMode = false;
  85578. /**
  85579. * Defines an observable called when the optimizer reaches the target frame rate
  85580. */
  85581. this.onSuccessObservable = new BABYLON.Observable();
  85582. /**
  85583. * Defines an observable called when the optimizer enables an optimization
  85584. */
  85585. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85586. /**
  85587. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85588. */
  85589. this.onFailureObservable = new BABYLON.Observable();
  85590. if (!options) {
  85591. this._options = new SceneOptimizerOptions();
  85592. }
  85593. else {
  85594. this._options = options;
  85595. }
  85596. if (this._options.targetFrameRate) {
  85597. this._targetFrameRate = this._options.targetFrameRate;
  85598. }
  85599. if (this._options.trackerDuration) {
  85600. this._trackerDuration = this._options.trackerDuration;
  85601. }
  85602. if (autoGeneratePriorities) {
  85603. var priority = 0;
  85604. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85605. var optim = _a[_i];
  85606. optim.priority = priority++;
  85607. }
  85608. }
  85609. this._improvementMode = improvementMode;
  85610. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85611. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85612. _this._sceneDisposeObserver = null;
  85613. _this.dispose();
  85614. });
  85615. }
  85616. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85617. /**
  85618. * Gets a boolean indicating if the optimizer is in improvement mode
  85619. */
  85620. get: function () {
  85621. return this._improvementMode;
  85622. },
  85623. enumerable: true,
  85624. configurable: true
  85625. });
  85626. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85627. /**
  85628. * Gets the current priority level (0 at start)
  85629. */
  85630. get: function () {
  85631. return this._currentPriorityLevel;
  85632. },
  85633. enumerable: true,
  85634. configurable: true
  85635. });
  85636. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85637. /**
  85638. * Gets the current frame rate checked by the SceneOptimizer
  85639. */
  85640. get: function () {
  85641. return this._currentFrameRate;
  85642. },
  85643. enumerable: true,
  85644. configurable: true
  85645. });
  85646. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85647. /**
  85648. * Gets or sets the current target frame rate (60 by default)
  85649. */
  85650. get: function () {
  85651. return this._targetFrameRate;
  85652. },
  85653. /**
  85654. * Gets or sets the current target frame rate (60 by default)
  85655. */
  85656. set: function (value) {
  85657. this._targetFrameRate = value;
  85658. },
  85659. enumerable: true,
  85660. configurable: true
  85661. });
  85662. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85663. /**
  85664. * Gets or sets the current interval between two checks (every 2000ms by default)
  85665. */
  85666. get: function () {
  85667. return this._trackerDuration;
  85668. },
  85669. /**
  85670. * Gets or sets the current interval between two checks (every 2000ms by default)
  85671. */
  85672. set: function (value) {
  85673. this._trackerDuration = value;
  85674. },
  85675. enumerable: true,
  85676. configurable: true
  85677. });
  85678. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85679. /**
  85680. * Gets the list of active optimizations
  85681. */
  85682. get: function () {
  85683. return this._options.optimizations;
  85684. },
  85685. enumerable: true,
  85686. configurable: true
  85687. });
  85688. /**
  85689. * Stops the current optimizer
  85690. */
  85691. SceneOptimizer.prototype.stop = function () {
  85692. this._isRunning = false;
  85693. };
  85694. /**
  85695. * Reset the optimizer to initial step (current priority level = 0)
  85696. */
  85697. SceneOptimizer.prototype.reset = function () {
  85698. this._currentPriorityLevel = 0;
  85699. };
  85700. /**
  85701. * Start the optimizer. By default it will try to reach a specific framerate
  85702. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  85703. */
  85704. SceneOptimizer.prototype.start = function () {
  85705. var _this = this;
  85706. if (this._isRunning) {
  85707. return;
  85708. }
  85709. this._isRunning = true;
  85710. // Let's wait for the scene to be ready before running our check
  85711. this._scene.executeWhenReady(function () {
  85712. setTimeout(function () {
  85713. _this._checkCurrentState();
  85714. }, _this._trackerDuration);
  85715. });
  85716. };
  85717. SceneOptimizer.prototype._checkCurrentState = function () {
  85718. var _this = this;
  85719. if (!this._isRunning) {
  85720. return;
  85721. }
  85722. var scene = this._scene;
  85723. var options = this._options;
  85724. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  85725. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  85726. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  85727. this._isRunning = false;
  85728. this.onSuccessObservable.notifyObservers(this);
  85729. return;
  85730. }
  85731. // Apply current level of optimizations
  85732. var allDone = true;
  85733. var noOptimizationApplied = true;
  85734. for (var index = 0; index < options.optimizations.length; index++) {
  85735. var optimization = options.optimizations[index];
  85736. if (optimization.priority === this._currentPriorityLevel) {
  85737. noOptimizationApplied = false;
  85738. allDone = allDone && optimization.apply(scene, this);
  85739. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  85740. }
  85741. }
  85742. // If no optimization was applied, this is a failure :(
  85743. if (noOptimizationApplied) {
  85744. this._isRunning = false;
  85745. this.onFailureObservable.notifyObservers(this);
  85746. return;
  85747. }
  85748. // If all optimizations were done, move to next level
  85749. if (allDone) {
  85750. this._currentPriorityLevel++;
  85751. }
  85752. // Let's the system running for a specific amount of time before checking FPS
  85753. scene.executeWhenReady(function () {
  85754. setTimeout(function () {
  85755. _this._checkCurrentState();
  85756. }, _this._trackerDuration);
  85757. });
  85758. };
  85759. /**
  85760. * Release all resources
  85761. */
  85762. SceneOptimizer.prototype.dispose = function () {
  85763. this.stop();
  85764. this.onSuccessObservable.clear();
  85765. this.onFailureObservable.clear();
  85766. this.onNewOptimizationAppliedObservable.clear();
  85767. if (this._sceneDisposeObserver) {
  85768. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  85769. }
  85770. };
  85771. /**
  85772. * Helper function to create a SceneOptimizer with one single line of code
  85773. * @param scene defines the scene to work on
  85774. * @param options defines the options to use with the SceneOptimizer
  85775. * @param onSuccess defines a callback to call on success
  85776. * @param onFailure defines a callback to call on failure
  85777. * @returns the new SceneOptimizer object
  85778. */
  85779. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85780. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85781. if (onSuccess) {
  85782. optimizer.onSuccessObservable.add(function () {
  85783. onSuccess();
  85784. });
  85785. }
  85786. if (onFailure) {
  85787. optimizer.onFailureObservable.add(function () {
  85788. onFailure();
  85789. });
  85790. }
  85791. optimizer.start();
  85792. return optimizer;
  85793. };
  85794. return SceneOptimizer;
  85795. }());
  85796. BABYLON.SceneOptimizer = SceneOptimizer;
  85797. })(BABYLON || (BABYLON = {}));
  85798. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85799. "use strict";
  85800. var BABYLON;
  85801. (function (BABYLON) {
  85802. var OutlineRenderer = /** @class */ (function () {
  85803. function OutlineRenderer(scene) {
  85804. this.zOffset = 1;
  85805. this._scene = scene;
  85806. }
  85807. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85808. var _this = this;
  85809. if (useOverlay === void 0) { useOverlay = false; }
  85810. var scene = this._scene;
  85811. var engine = this._scene.getEngine();
  85812. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85813. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85814. return;
  85815. }
  85816. var mesh = subMesh.getRenderingMesh();
  85817. var material = subMesh.getMaterial();
  85818. if (!material || !scene.activeCamera) {
  85819. return;
  85820. }
  85821. engine.enableEffect(this._effect);
  85822. // Logarithmic depth
  85823. if (material.useLogarithmicDepth) {
  85824. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85825. }
  85826. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85827. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85828. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85829. // Bones
  85830. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85831. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85832. }
  85833. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85834. // Alpha test
  85835. if (material && material.needAlphaTesting()) {
  85836. var alphaTexture = material.getAlphaTestTexture();
  85837. if (alphaTexture) {
  85838. this._effect.setTexture("diffuseSampler", alphaTexture);
  85839. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85840. }
  85841. }
  85842. engine.setZOffset(-this.zOffset);
  85843. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85844. engine.setZOffset(0);
  85845. };
  85846. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85847. var defines = [];
  85848. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85849. var mesh = subMesh.getMesh();
  85850. var material = subMesh.getMaterial();
  85851. if (material) {
  85852. // Alpha test
  85853. if (material.needAlphaTesting()) {
  85854. defines.push("#define ALPHATEST");
  85855. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85856. attribs.push(BABYLON.VertexBuffer.UVKind);
  85857. defines.push("#define UV1");
  85858. }
  85859. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85860. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85861. defines.push("#define UV2");
  85862. }
  85863. }
  85864. //Logarithmic depth
  85865. if (material.useLogarithmicDepth) {
  85866. defines.push("#define LOGARITHMICDEPTH");
  85867. }
  85868. }
  85869. // Bones
  85870. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85871. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85872. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85873. if (mesh.numBoneInfluencers > 4) {
  85874. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85875. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85876. }
  85877. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85878. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85879. }
  85880. else {
  85881. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85882. }
  85883. // Instances
  85884. if (useInstances) {
  85885. defines.push("#define INSTANCES");
  85886. attribs.push("world0");
  85887. attribs.push("world1");
  85888. attribs.push("world2");
  85889. attribs.push("world3");
  85890. }
  85891. // Get correct effect
  85892. var join = defines.join("\n");
  85893. if (this._cachedDefines !== join) {
  85894. this._cachedDefines = join;
  85895. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85896. }
  85897. return this._effect.isReady();
  85898. };
  85899. return OutlineRenderer;
  85900. }());
  85901. BABYLON.OutlineRenderer = OutlineRenderer;
  85902. })(BABYLON || (BABYLON = {}));
  85903. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85904. "use strict";
  85905. var BABYLON;
  85906. (function (BABYLON) {
  85907. var FaceAdjacencies = /** @class */ (function () {
  85908. function FaceAdjacencies() {
  85909. this.edges = new Array();
  85910. this.edgesConnectedCount = 0;
  85911. }
  85912. return FaceAdjacencies;
  85913. }());
  85914. var EdgesRenderer = /** @class */ (function () {
  85915. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85916. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85917. if (epsilon === void 0) { epsilon = 0.95; }
  85918. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85919. this.edgesWidthScalerForOrthographic = 1000.0;
  85920. this.edgesWidthScalerForPerspective = 50.0;
  85921. this._linesPositions = new Array();
  85922. this._linesNormals = new Array();
  85923. this._linesIndices = new Array();
  85924. this._buffers = {};
  85925. this._checkVerticesInsteadOfIndices = false;
  85926. this._source = source;
  85927. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85928. this._epsilon = epsilon;
  85929. this._prepareRessources();
  85930. this._generateEdgesLines();
  85931. }
  85932. EdgesRenderer.prototype._prepareRessources = function () {
  85933. if (this._lineShader) {
  85934. return;
  85935. }
  85936. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85937. attributes: ["position", "normal"],
  85938. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85939. });
  85940. this._lineShader.disableDepthWrite = true;
  85941. this._lineShader.backFaceCulling = false;
  85942. };
  85943. EdgesRenderer.prototype._rebuild = function () {
  85944. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85945. if (buffer) {
  85946. buffer._rebuild();
  85947. }
  85948. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85949. if (buffer) {
  85950. buffer._rebuild();
  85951. }
  85952. var scene = this._source.getScene();
  85953. var engine = scene.getEngine();
  85954. this._ib = engine.createIndexBuffer(this._linesIndices);
  85955. };
  85956. EdgesRenderer.prototype.dispose = function () {
  85957. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85958. if (buffer) {
  85959. buffer.dispose();
  85960. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85961. }
  85962. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85963. if (buffer) {
  85964. buffer.dispose();
  85965. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85966. }
  85967. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85968. this._lineShader.dispose();
  85969. };
  85970. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85971. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85972. return 0;
  85973. }
  85974. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85975. return 1;
  85976. }
  85977. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85978. return 2;
  85979. }
  85980. return -1;
  85981. };
  85982. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85983. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85984. return 0;
  85985. }
  85986. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85987. return 1;
  85988. }
  85989. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85990. return 2;
  85991. }
  85992. return -1;
  85993. };
  85994. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85995. var needToCreateLine;
  85996. if (edge === undefined) {
  85997. needToCreateLine = true;
  85998. }
  85999. else {
  86000. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  86001. needToCreateLine = dotProduct < this._epsilon;
  86002. }
  86003. if (needToCreateLine) {
  86004. var offset = this._linesPositions.length / 3;
  86005. var normal = p0.subtract(p1);
  86006. normal.normalize();
  86007. // Positions
  86008. this._linesPositions.push(p0.x);
  86009. this._linesPositions.push(p0.y);
  86010. this._linesPositions.push(p0.z);
  86011. this._linesPositions.push(p0.x);
  86012. this._linesPositions.push(p0.y);
  86013. this._linesPositions.push(p0.z);
  86014. this._linesPositions.push(p1.x);
  86015. this._linesPositions.push(p1.y);
  86016. this._linesPositions.push(p1.z);
  86017. this._linesPositions.push(p1.x);
  86018. this._linesPositions.push(p1.y);
  86019. this._linesPositions.push(p1.z);
  86020. // Normals
  86021. this._linesNormals.push(p1.x);
  86022. this._linesNormals.push(p1.y);
  86023. this._linesNormals.push(p1.z);
  86024. this._linesNormals.push(-1);
  86025. this._linesNormals.push(p1.x);
  86026. this._linesNormals.push(p1.y);
  86027. this._linesNormals.push(p1.z);
  86028. this._linesNormals.push(1);
  86029. this._linesNormals.push(p0.x);
  86030. this._linesNormals.push(p0.y);
  86031. this._linesNormals.push(p0.z);
  86032. this._linesNormals.push(-1);
  86033. this._linesNormals.push(p0.x);
  86034. this._linesNormals.push(p0.y);
  86035. this._linesNormals.push(p0.z);
  86036. this._linesNormals.push(1);
  86037. // Indices
  86038. this._linesIndices.push(offset);
  86039. this._linesIndices.push(offset + 1);
  86040. this._linesIndices.push(offset + 2);
  86041. this._linesIndices.push(offset);
  86042. this._linesIndices.push(offset + 2);
  86043. this._linesIndices.push(offset + 3);
  86044. }
  86045. };
  86046. EdgesRenderer.prototype._generateEdgesLines = function () {
  86047. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86048. var indices = this._source.getIndices();
  86049. if (!indices || !positions) {
  86050. return;
  86051. }
  86052. // First let's find adjacencies
  86053. var adjacencies = new Array();
  86054. var faceNormals = new Array();
  86055. var index;
  86056. var faceAdjacencies;
  86057. // Prepare faces
  86058. for (index = 0; index < indices.length; index += 3) {
  86059. faceAdjacencies = new FaceAdjacencies();
  86060. var p0Index = indices[index];
  86061. var p1Index = indices[index + 1];
  86062. var p2Index = indices[index + 2];
  86063. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86064. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86065. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86066. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86067. faceNormal.normalize();
  86068. faceNormals.push(faceNormal);
  86069. adjacencies.push(faceAdjacencies);
  86070. }
  86071. // Scan
  86072. for (index = 0; index < adjacencies.length; index++) {
  86073. faceAdjacencies = adjacencies[index];
  86074. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86075. var otherFaceAdjacencies = adjacencies[otherIndex];
  86076. if (faceAdjacencies.edgesConnectedCount === 3) {
  86077. break;
  86078. }
  86079. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86080. continue;
  86081. }
  86082. var otherP0 = indices[otherIndex * 3];
  86083. var otherP1 = indices[otherIndex * 3 + 1];
  86084. var otherP2 = indices[otherIndex * 3 + 2];
  86085. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86086. var otherEdgeIndex = 0;
  86087. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86088. continue;
  86089. }
  86090. switch (edgeIndex) {
  86091. case 0:
  86092. if (this._checkVerticesInsteadOfIndices) {
  86093. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86094. }
  86095. else {
  86096. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86097. }
  86098. break;
  86099. case 1:
  86100. if (this._checkVerticesInsteadOfIndices) {
  86101. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86102. }
  86103. else {
  86104. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86105. }
  86106. break;
  86107. case 2:
  86108. if (this._checkVerticesInsteadOfIndices) {
  86109. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86110. }
  86111. else {
  86112. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86113. }
  86114. break;
  86115. }
  86116. if (otherEdgeIndex === -1) {
  86117. continue;
  86118. }
  86119. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86120. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86121. faceAdjacencies.edgesConnectedCount++;
  86122. otherFaceAdjacencies.edgesConnectedCount++;
  86123. if (faceAdjacencies.edgesConnectedCount === 3) {
  86124. break;
  86125. }
  86126. }
  86127. }
  86128. }
  86129. // Create lines
  86130. for (index = 0; index < adjacencies.length; index++) {
  86131. // 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
  86132. var current = adjacencies[index];
  86133. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86134. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86135. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86136. }
  86137. // Merge into a single mesh
  86138. var engine = this._source.getScene().getEngine();
  86139. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86140. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86141. this._ib = engine.createIndexBuffer(this._linesIndices);
  86142. this._indicesCount = this._linesIndices.length;
  86143. };
  86144. EdgesRenderer.prototype.render = function () {
  86145. var scene = this._source.getScene();
  86146. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86147. return;
  86148. }
  86149. var engine = scene.getEngine();
  86150. this._lineShader._preBind();
  86151. // VBOs
  86152. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86153. scene.resetCachedMaterial();
  86154. this._lineShader.setColor4("color", this._source.edgesColor);
  86155. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86156. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86157. }
  86158. else {
  86159. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86160. }
  86161. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86162. this._lineShader.bind(this._source.getWorldMatrix());
  86163. // Draw order
  86164. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86165. this._lineShader.unbind();
  86166. engine.setDepthWrite(true);
  86167. };
  86168. return EdgesRenderer;
  86169. }());
  86170. BABYLON.EdgesRenderer = EdgesRenderer;
  86171. })(BABYLON || (BABYLON = {}));
  86172. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86173. "use strict";
  86174. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86175. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86176. s = arguments[i];
  86177. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86178. t[p] = s[p];
  86179. }
  86180. return t;
  86181. };
  86182. var BABYLON;
  86183. (function (BABYLON) {
  86184. /**
  86185. * The effect layer Helps adding post process effect blended with the main pass.
  86186. *
  86187. * This can be for instance use to generate glow or higlight effects on the scene.
  86188. *
  86189. * The effect layer class can not be used directly and is intented to inherited from to be
  86190. * customized per effects.
  86191. */
  86192. var EffectLayer = /** @class */ (function () {
  86193. /**
  86194. * Instantiates a new effect Layer and references it in the scene.
  86195. * @param name The name of the layer
  86196. * @param scene The scene to use the layer in
  86197. */
  86198. function EffectLayer(
  86199. /** The Friendly of the effect in the scene */
  86200. name, scene) {
  86201. this.name = name;
  86202. this._vertexBuffers = {};
  86203. this._maxSize = 0;
  86204. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86205. this._shouldRender = true;
  86206. this._postProcesses = [];
  86207. this._textures = [];
  86208. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86209. /**
  86210. * The clear color of the texture used to generate the glow map.
  86211. */
  86212. this.neutralColor = new BABYLON.Color4();
  86213. /**
  86214. * Specifies wether the highlight layer is enabled or not.
  86215. */
  86216. this.isEnabled = true;
  86217. /**
  86218. * An event triggered when the effect layer has been disposed.
  86219. */
  86220. this.onDisposeObservable = new BABYLON.Observable();
  86221. /**
  86222. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86223. */
  86224. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86225. /**
  86226. * An event triggered when the generated texture is being merged in the scene.
  86227. */
  86228. this.onBeforeComposeObservable = new BABYLON.Observable();
  86229. /**
  86230. * An event triggered when the generated texture has been merged in the scene.
  86231. */
  86232. this.onAfterComposeObservable = new BABYLON.Observable();
  86233. /**
  86234. * An event triggered when the efffect layer changes its size.
  86235. */
  86236. this.onSizeChangedObservable = new BABYLON.Observable();
  86237. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86238. this._engine = scene.getEngine();
  86239. this._maxSize = this._engine.getCaps().maxTextureSize;
  86240. this._scene.effectLayers.push(this);
  86241. // Generate Buffers
  86242. this._generateIndexBuffer();
  86243. this._genrateVertexBuffer();
  86244. }
  86245. Object.defineProperty(EffectLayer.prototype, "camera", {
  86246. /**
  86247. * Gets the camera attached to the layer.
  86248. */
  86249. get: function () {
  86250. return this._effectLayerOptions.camera;
  86251. },
  86252. enumerable: true,
  86253. configurable: true
  86254. });
  86255. /**
  86256. * Initializes the effect layer with the required options.
  86257. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86258. */
  86259. EffectLayer.prototype._init = function (options) {
  86260. // Adapt options
  86261. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86262. this._setMainTextureSize();
  86263. this._createMainTexture();
  86264. this._createTextureAndPostProcesses();
  86265. this._mergeEffect = this._createMergeEffect();
  86266. };
  86267. /**
  86268. * Generates the index buffer of the full screen quad blending to the main canvas.
  86269. */
  86270. EffectLayer.prototype._generateIndexBuffer = function () {
  86271. // Indices
  86272. var indices = [];
  86273. indices.push(0);
  86274. indices.push(1);
  86275. indices.push(2);
  86276. indices.push(0);
  86277. indices.push(2);
  86278. indices.push(3);
  86279. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86280. };
  86281. /**
  86282. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86283. */
  86284. EffectLayer.prototype._genrateVertexBuffer = function () {
  86285. // VBO
  86286. var vertices = [];
  86287. vertices.push(1, 1);
  86288. vertices.push(-1, 1);
  86289. vertices.push(-1, -1);
  86290. vertices.push(1, -1);
  86291. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86292. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86293. };
  86294. /**
  86295. * Sets the main texture desired size which is the closest power of two
  86296. * of the engine canvas size.
  86297. */
  86298. EffectLayer.prototype._setMainTextureSize = function () {
  86299. if (this._effectLayerOptions.mainTextureFixedSize) {
  86300. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86301. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86302. }
  86303. else {
  86304. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86305. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86306. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86307. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86308. }
  86309. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86310. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86311. };
  86312. /**
  86313. * Creates the main texture for the effect layer.
  86314. */
  86315. EffectLayer.prototype._createMainTexture = function () {
  86316. var _this = this;
  86317. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86318. width: this._mainTextureDesiredSize.width,
  86319. height: this._mainTextureDesiredSize.height
  86320. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86321. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86322. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86323. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86324. this._mainTexture.anisotropicFilteringLevel = 1;
  86325. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86326. this._mainTexture.renderParticles = false;
  86327. this._mainTexture.renderList = null;
  86328. this._mainTexture.ignoreCameraViewport = true;
  86329. // Custom render function
  86330. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86331. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86332. var index;
  86333. var engine = _this._scene.getEngine();
  86334. if (depthOnlySubMeshes.length) {
  86335. engine.setColorWrite(false);
  86336. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86337. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86338. }
  86339. engine.setColorWrite(true);
  86340. }
  86341. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86342. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86343. }
  86344. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86345. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86346. }
  86347. for (index = 0; index < transparentSubMeshes.length; index++) {
  86348. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86349. }
  86350. };
  86351. this._mainTexture.onClearObservable.add(function (engine) {
  86352. engine.clear(_this.neutralColor, true, true, true);
  86353. });
  86354. };
  86355. /**
  86356. * Checks for the readiness of the element composing the layer.
  86357. * @param subMesh the mesh to check for
  86358. * @param useInstances specify wether or not to use instances to render the mesh
  86359. * @param emissiveTexture the associated emissive texture used to generate the glow
  86360. * @return true if ready otherwise, false
  86361. */
  86362. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86363. var material = subMesh.getMaterial();
  86364. if (!material) {
  86365. return false;
  86366. }
  86367. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86368. return false;
  86369. }
  86370. var defines = [];
  86371. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86372. var mesh = subMesh.getMesh();
  86373. var uv1 = false;
  86374. var uv2 = false;
  86375. // Alpha test
  86376. if (material && material.needAlphaTesting()) {
  86377. var alphaTexture = material.getAlphaTestTexture();
  86378. if (alphaTexture) {
  86379. defines.push("#define ALPHATEST");
  86380. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86381. alphaTexture.coordinatesIndex === 1) {
  86382. defines.push("#define DIFFUSEUV2");
  86383. uv2 = true;
  86384. }
  86385. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86386. defines.push("#define DIFFUSEUV1");
  86387. uv1 = true;
  86388. }
  86389. }
  86390. }
  86391. // Emissive
  86392. if (emissiveTexture) {
  86393. defines.push("#define EMISSIVE");
  86394. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86395. emissiveTexture.coordinatesIndex === 1) {
  86396. defines.push("#define EMISSIVEUV2");
  86397. uv2 = true;
  86398. }
  86399. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86400. defines.push("#define EMISSIVEUV1");
  86401. uv1 = true;
  86402. }
  86403. }
  86404. if (uv1) {
  86405. attribs.push(BABYLON.VertexBuffer.UVKind);
  86406. defines.push("#define UV1");
  86407. }
  86408. if (uv2) {
  86409. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86410. defines.push("#define UV2");
  86411. }
  86412. // Bones
  86413. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86414. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86415. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86416. if (mesh.numBoneInfluencers > 4) {
  86417. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86418. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86419. }
  86420. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86421. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86422. }
  86423. else {
  86424. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86425. }
  86426. // Morph targets
  86427. var manager = mesh.morphTargetManager;
  86428. var morphInfluencers = 0;
  86429. if (manager) {
  86430. if (manager.numInfluencers > 0) {
  86431. defines.push("#define MORPHTARGETS");
  86432. morphInfluencers = manager.numInfluencers;
  86433. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  86434. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  86435. }
  86436. }
  86437. // Instances
  86438. if (useInstances) {
  86439. defines.push("#define INSTANCES");
  86440. attribs.push("world0");
  86441. attribs.push("world1");
  86442. attribs.push("world2");
  86443. attribs.push("world3");
  86444. }
  86445. // Get correct effect
  86446. var join = defines.join("\n");
  86447. if (this._cachedDefines !== join) {
  86448. this._cachedDefines = join;
  86449. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  86450. }
  86451. return this._effectLayerMapGenerationEffect.isReady();
  86452. };
  86453. /**
  86454. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86455. */
  86456. EffectLayer.prototype.render = function () {
  86457. var currentEffect = this._mergeEffect;
  86458. // Check
  86459. if (!currentEffect.isReady())
  86460. return;
  86461. for (var i = 0; i < this._postProcesses.length; i++) {
  86462. if (!this._postProcesses[i].isReady()) {
  86463. return;
  86464. }
  86465. }
  86466. var engine = this._scene.getEngine();
  86467. this.onBeforeComposeObservable.notifyObservers(this);
  86468. // Render
  86469. engine.enableEffect(currentEffect);
  86470. engine.setState(false);
  86471. // VBOs
  86472. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86473. // Cache
  86474. var previousAlphaMode = engine.getAlphaMode();
  86475. // Go Blend.
  86476. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86477. // Blends the map on the main canvas.
  86478. this._internalRender(currentEffect);
  86479. // Restore Alpha
  86480. engine.setAlphaMode(previousAlphaMode);
  86481. this.onAfterComposeObservable.notifyObservers(this);
  86482. // Handle size changes.
  86483. var size = this._mainTexture.getSize();
  86484. this._setMainTextureSize();
  86485. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86486. // Recreate RTT and post processes on size change.
  86487. this.onSizeChangedObservable.notifyObservers(this);
  86488. this._disposeTextureAndPostProcesses();
  86489. this._createMainTexture();
  86490. this._createTextureAndPostProcesses();
  86491. }
  86492. };
  86493. /**
  86494. * Determine if a given mesh will be used in the current effect.
  86495. * @param mesh mesh to test
  86496. * @returns true if the mesh will be used
  86497. */
  86498. EffectLayer.prototype.hasMesh = function (mesh) {
  86499. return true;
  86500. };
  86501. /**
  86502. * Returns true if the layer contains information to display, otherwise false.
  86503. * @returns true if the glow layer should be rendered
  86504. */
  86505. EffectLayer.prototype.shouldRender = function () {
  86506. return this.isEnabled && this._shouldRender;
  86507. };
  86508. /**
  86509. * Returns true if the mesh should render, otherwise false.
  86510. * @param mesh The mesh to render
  86511. * @returns true if it should render otherwise false
  86512. */
  86513. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86514. return true;
  86515. };
  86516. /**
  86517. * Returns true if the mesh should render, otherwise false.
  86518. * @param mesh The mesh to render
  86519. * @returns true if it should render otherwise false
  86520. */
  86521. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86522. return true;
  86523. };
  86524. /**
  86525. * Renders the submesh passed in parameter to the generation map.
  86526. */
  86527. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86528. var _this = this;
  86529. if (!this.shouldRender()) {
  86530. return;
  86531. }
  86532. var material = subMesh.getMaterial();
  86533. var mesh = subMesh.getRenderingMesh();
  86534. var scene = this._scene;
  86535. var engine = scene.getEngine();
  86536. if (!material) {
  86537. return;
  86538. }
  86539. // Do not block in blend mode.
  86540. if (material.needAlphaBlendingForMesh(mesh)) {
  86541. return;
  86542. }
  86543. // Culling
  86544. engine.setState(material.backFaceCulling);
  86545. // Managing instances
  86546. var batch = mesh._getInstancesRenderList(subMesh._id);
  86547. if (batch.mustReturn) {
  86548. return;
  86549. }
  86550. // Early Exit per mesh
  86551. if (!this._shouldRenderMesh(mesh)) {
  86552. return;
  86553. }
  86554. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86555. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86556. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86557. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86558. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86559. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86560. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86561. // Alpha test
  86562. if (material && material.needAlphaTesting()) {
  86563. var alphaTexture = material.getAlphaTestTexture();
  86564. if (alphaTexture) {
  86565. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86566. var textureMatrix = alphaTexture.getTextureMatrix();
  86567. if (textureMatrix) {
  86568. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86569. }
  86570. }
  86571. }
  86572. // Glow emissive only
  86573. if (this._emissiveTextureAndColor.texture) {
  86574. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86575. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86576. }
  86577. // Bones
  86578. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86579. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86580. }
  86581. // Morph targets
  86582. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  86583. // Draw
  86584. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86585. }
  86586. else {
  86587. // Need to reset refresh rate of the shadowMap
  86588. this._mainTexture.resetRefreshCounter();
  86589. }
  86590. };
  86591. /**
  86592. * Rebuild the required buffers.
  86593. * @ignore Internal use only.
  86594. */
  86595. EffectLayer.prototype._rebuild = function () {
  86596. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86597. if (vb) {
  86598. vb._rebuild();
  86599. }
  86600. this._generateIndexBuffer();
  86601. };
  86602. /**
  86603. * Dispose only the render target textures and post process.
  86604. */
  86605. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86606. this._mainTexture.dispose();
  86607. for (var i = 0; i < this._postProcesses.length; i++) {
  86608. if (this._postProcesses[i]) {
  86609. this._postProcesses[i].dispose();
  86610. }
  86611. }
  86612. this._postProcesses = [];
  86613. for (var i = 0; i < this._textures.length; i++) {
  86614. if (this._textures[i]) {
  86615. this._textures[i].dispose();
  86616. }
  86617. }
  86618. this._textures = [];
  86619. };
  86620. /**
  86621. * Dispose the highlight layer and free resources.
  86622. */
  86623. EffectLayer.prototype.dispose = function () {
  86624. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86625. if (vertexBuffer) {
  86626. vertexBuffer.dispose();
  86627. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86628. }
  86629. if (this._indexBuffer) {
  86630. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86631. this._indexBuffer = null;
  86632. }
  86633. // Clean textures and post processes
  86634. this._disposeTextureAndPostProcesses();
  86635. // Remove from scene
  86636. var index = this._scene.effectLayers.indexOf(this, 0);
  86637. if (index > -1) {
  86638. this._scene.effectLayers.splice(index, 1);
  86639. }
  86640. // Callback
  86641. this.onDisposeObservable.notifyObservers(this);
  86642. this.onDisposeObservable.clear();
  86643. this.onBeforeRenderMainTextureObservable.clear();
  86644. this.onBeforeComposeObservable.clear();
  86645. this.onAfterComposeObservable.clear();
  86646. this.onSizeChangedObservable.clear();
  86647. };
  86648. return EffectLayer;
  86649. }());
  86650. BABYLON.EffectLayer = EffectLayer;
  86651. })(BABYLON || (BABYLON = {}));
  86652. //# sourceMappingURL=babylon.effectLayer.js.map
  86653. "use strict";
  86654. var BABYLON;
  86655. (function (BABYLON) {
  86656. /**
  86657. * Special Glow Blur post process only blurring the alpha channel
  86658. * It enforces keeping the most luminous color in the color channel.
  86659. */
  86660. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86661. __extends(GlowBlurPostProcess, _super);
  86662. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86663. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86664. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86665. _this.direction = direction;
  86666. _this.kernel = kernel;
  86667. _this.onApplyObservable.add(function (effect) {
  86668. effect.setFloat2("screenSize", _this.width, _this.height);
  86669. effect.setVector2("direction", _this.direction);
  86670. effect.setFloat("blurWidth", _this.kernel);
  86671. });
  86672. return _this;
  86673. }
  86674. return GlowBlurPostProcess;
  86675. }(BABYLON.PostProcess));
  86676. /**
  86677. * The highlight layer Helps adding a glow effect around a mesh.
  86678. *
  86679. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86680. * glowy meshes to your scene.
  86681. *
  86682. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86683. */
  86684. var HighlightLayer = /** @class */ (function (_super) {
  86685. __extends(HighlightLayer, _super);
  86686. /**
  86687. * Instantiates a new highlight Layer and references it to the scene..
  86688. * @param name The name of the layer
  86689. * @param scene The scene to use the layer in
  86690. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86691. */
  86692. function HighlightLayer(name, scene, options) {
  86693. var _this = _super.call(this, name, scene) || this;
  86694. _this.name = name;
  86695. /**
  86696. * Specifies whether or not the inner glow is ACTIVE in the layer.
  86697. */
  86698. _this.innerGlow = true;
  86699. /**
  86700. * Specifies whether or not the outer glow is ACTIVE in the layer.
  86701. */
  86702. _this.outerGlow = true;
  86703. /**
  86704. * An event triggered when the highlight layer is being blurred.
  86705. */
  86706. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86707. /**
  86708. * An event triggered when the highlight layer has been blurred.
  86709. */
  86710. _this.onAfterBlurObservable = new BABYLON.Observable();
  86711. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86712. _this._meshes = {};
  86713. _this._excludedMeshes = {};
  86714. _this.neutralColor = HighlightLayer.NeutralColor;
  86715. // Warn on stencil
  86716. if (!_this._engine.isStencilEnable) {
  86717. 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 }");
  86718. }
  86719. // Adapt options
  86720. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86721. // Initialize the layer
  86722. _this._init({
  86723. alphaBlendingMode: _this._options.alphaBlendingMode,
  86724. camera: _this._options.camera,
  86725. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86726. mainTextureRatio: _this._options.mainTextureRatio
  86727. });
  86728. // Do not render as long as no meshes have been added
  86729. _this._shouldRender = false;
  86730. return _this;
  86731. }
  86732. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  86733. /**
  86734. * Gets the horizontal size of the blur.
  86735. */
  86736. get: function () {
  86737. return this._horizontalBlurPostprocess.kernel;
  86738. },
  86739. /**
  86740. * Specifies the horizontal size of the blur.
  86741. */
  86742. set: function (value) {
  86743. this._horizontalBlurPostprocess.kernel = value;
  86744. },
  86745. enumerable: true,
  86746. configurable: true
  86747. });
  86748. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  86749. /**
  86750. * Gets the vertical size of the blur.
  86751. */
  86752. get: function () {
  86753. return this._verticalBlurPostprocess.kernel;
  86754. },
  86755. /**
  86756. * Specifies the vertical size of the blur.
  86757. */
  86758. set: function (value) {
  86759. this._verticalBlurPostprocess.kernel = value;
  86760. },
  86761. enumerable: true,
  86762. configurable: true
  86763. });
  86764. /**
  86765. * Get the effect name of the layer.
  86766. * @return The effect name
  86767. */
  86768. HighlightLayer.prototype.getEffectName = function () {
  86769. return HighlightLayer.EffectName;
  86770. };
  86771. /**
  86772. * Create the merge effect. This is the shader use to blit the information back
  86773. * to the main canvas at the end of the scene rendering.
  86774. */
  86775. HighlightLayer.prototype._createMergeEffect = function () {
  86776. // Effect
  86777. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  86778. };
  86779. /**
  86780. * Creates the render target textures and post processes used in the highlight layer.
  86781. */
  86782. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  86783. var _this = this;
  86784. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  86785. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  86786. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86787. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86788. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  86789. width: blurTextureWidth,
  86790. height: blurTextureHeight
  86791. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86792. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86793. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86794. this._blurTexture.anisotropicFilteringLevel = 16;
  86795. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86796. this._blurTexture.renderParticles = false;
  86797. this._blurTexture.ignoreCameraViewport = true;
  86798. this._textures = [this._blurTexture];
  86799. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86800. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86801. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86802. effect.setTexture("textureSampler", _this._mainTexture);
  86803. });
  86804. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86805. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86806. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86807. });
  86808. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86809. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86810. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86811. });
  86812. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86813. }
  86814. else {
  86815. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86816. width: blurTextureWidth,
  86817. height: blurTextureHeight
  86818. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86819. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86820. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86821. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86822. effect.setTexture("textureSampler", _this._mainTexture);
  86823. });
  86824. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86825. width: blurTextureWidth,
  86826. height: blurTextureHeight
  86827. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86828. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86829. }
  86830. this._mainTexture.onAfterUnbindObservable.add(function () {
  86831. _this.onBeforeBlurObservable.notifyObservers(_this);
  86832. var internalTexture = _this._blurTexture.getInternalTexture();
  86833. if (internalTexture) {
  86834. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86835. }
  86836. _this.onAfterBlurObservable.notifyObservers(_this);
  86837. });
  86838. // Prevent autoClear.
  86839. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86840. };
  86841. /**
  86842. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86843. */
  86844. HighlightLayer.prototype.needStencil = function () {
  86845. return true;
  86846. };
  86847. /**
  86848. * Checks for the readiness of the element composing the layer.
  86849. * @param subMesh the mesh to check for
  86850. * @param useInstances specify wether or not to use instances to render the mesh
  86851. * @param emissiveTexture the associated emissive texture used to generate the glow
  86852. * @return true if ready otherwise, false
  86853. */
  86854. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86855. var material = subMesh.getMaterial();
  86856. var mesh = subMesh.getRenderingMesh();
  86857. if (!material || !mesh || !this._meshes) {
  86858. return false;
  86859. }
  86860. var emissiveTexture = null;
  86861. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86862. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86863. emissiveTexture = material.emissiveTexture;
  86864. }
  86865. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86866. };
  86867. /**
  86868. * Implementation specific of rendering the generating effect on the main canvas.
  86869. * @param effect The effect used to render through
  86870. */
  86871. HighlightLayer.prototype._internalRender = function (effect) {
  86872. // Texture
  86873. effect.setTexture("textureSampler", this._blurTexture);
  86874. // Cache
  86875. var engine = this._engine;
  86876. var previousStencilBuffer = engine.getStencilBuffer();
  86877. var previousStencilFunction = engine.getStencilFunction();
  86878. var previousStencilMask = engine.getStencilMask();
  86879. var previousStencilOperationPass = engine.getStencilOperationPass();
  86880. var previousStencilOperationFail = engine.getStencilOperationFail();
  86881. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86882. var previousStencilReference = engine.getStencilFunctionReference();
  86883. // Stencil operations
  86884. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86885. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86886. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86887. // Draw order
  86888. engine.setStencilMask(0x00);
  86889. engine.setStencilBuffer(true);
  86890. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86891. // 2 passes inner outer
  86892. if (this.outerGlow) {
  86893. effect.setFloat("offset", 0);
  86894. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86895. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86896. }
  86897. if (this.innerGlow) {
  86898. effect.setFloat("offset", 1);
  86899. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86900. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86901. }
  86902. // Restore Cache
  86903. engine.setStencilFunction(previousStencilFunction);
  86904. engine.setStencilMask(previousStencilMask);
  86905. engine.setStencilBuffer(previousStencilBuffer);
  86906. engine.setStencilOperationPass(previousStencilOperationPass);
  86907. engine.setStencilOperationFail(previousStencilOperationFail);
  86908. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86909. engine.setStencilFunctionReference(previousStencilReference);
  86910. };
  86911. /**
  86912. * Returns true if the layer contains information to display, otherwise false.
  86913. */
  86914. HighlightLayer.prototype.shouldRender = function () {
  86915. if (_super.prototype.shouldRender.call(this)) {
  86916. return this._meshes ? true : false;
  86917. }
  86918. return false;
  86919. };
  86920. /**
  86921. * Returns true if the mesh should render, otherwise false.
  86922. * @param mesh The mesh to render
  86923. * @returns true if it should render otherwise false
  86924. */
  86925. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86926. // Excluded Mesh
  86927. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86928. return false;
  86929. }
  86930. ;
  86931. return true;
  86932. };
  86933. /**
  86934. * Sets the required values for both the emissive texture and and the main color.
  86935. */
  86936. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86937. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86938. if (highlightLayerMesh) {
  86939. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86940. }
  86941. else {
  86942. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86943. }
  86944. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86945. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86946. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86947. }
  86948. else {
  86949. this._emissiveTextureAndColor.texture = null;
  86950. }
  86951. };
  86952. /**
  86953. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86954. * @param mesh The mesh to exclude from the highlight layer
  86955. */
  86956. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86957. if (!this._excludedMeshes) {
  86958. return;
  86959. }
  86960. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86961. if (!meshExcluded) {
  86962. this._excludedMeshes[mesh.uniqueId] = {
  86963. mesh: mesh,
  86964. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86965. mesh.getEngine().setStencilBuffer(false);
  86966. }),
  86967. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86968. mesh.getEngine().setStencilBuffer(true);
  86969. }),
  86970. };
  86971. }
  86972. };
  86973. /**
  86974. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86975. * @param mesh The mesh to highlight
  86976. */
  86977. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86978. if (!this._excludedMeshes) {
  86979. return;
  86980. }
  86981. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86982. if (meshExcluded) {
  86983. if (meshExcluded.beforeRender) {
  86984. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86985. }
  86986. if (meshExcluded.afterRender) {
  86987. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86988. }
  86989. }
  86990. this._excludedMeshes[mesh.uniqueId] = null;
  86991. };
  86992. /**
  86993. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86994. * @param mesh mesh to test
  86995. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86996. */
  86997. HighlightLayer.prototype.hasMesh = function (mesh) {
  86998. if (!this._meshes) {
  86999. return false;
  87000. }
  87001. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  87002. };
  87003. /**
  87004. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  87005. * @param mesh The mesh to highlight
  87006. * @param color The color of the highlight
  87007. * @param glowEmissiveOnly Extract the glow from the emissive texture
  87008. */
  87009. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  87010. var _this = this;
  87011. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  87012. if (!this._meshes) {
  87013. return;
  87014. }
  87015. var meshHighlight = this._meshes[mesh.uniqueId];
  87016. if (meshHighlight) {
  87017. meshHighlight.color = color;
  87018. }
  87019. else {
  87020. this._meshes[mesh.uniqueId] = {
  87021. mesh: mesh,
  87022. color: color,
  87023. // Lambda required for capture due to Observable this context
  87024. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  87025. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  87026. _this._defaultStencilReference(mesh);
  87027. }
  87028. else {
  87029. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  87030. }
  87031. }),
  87032. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  87033. glowEmissiveOnly: glowEmissiveOnly
  87034. };
  87035. }
  87036. this._shouldRender = true;
  87037. };
  87038. /**
  87039. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87040. * @param mesh The mesh to highlight
  87041. */
  87042. HighlightLayer.prototype.removeMesh = function (mesh) {
  87043. if (!this._meshes) {
  87044. return;
  87045. }
  87046. var meshHighlight = this._meshes[mesh.uniqueId];
  87047. if (meshHighlight) {
  87048. if (meshHighlight.observerHighlight) {
  87049. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87050. }
  87051. if (meshHighlight.observerDefault) {
  87052. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87053. }
  87054. delete this._meshes[mesh.uniqueId];
  87055. }
  87056. this._shouldRender = false;
  87057. for (var meshHighlightToCheck in this._meshes) {
  87058. if (this._meshes[meshHighlightToCheck]) {
  87059. this._shouldRender = true;
  87060. break;
  87061. }
  87062. }
  87063. };
  87064. /**
  87065. * Force the stencil to the normal expected value for none glowing parts
  87066. */
  87067. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87068. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87069. };
  87070. /**
  87071. * Free any resources and references associated to a mesh.
  87072. * Internal use
  87073. * @param mesh The mesh to free.
  87074. */
  87075. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87076. this.removeMesh(mesh);
  87077. this.removeExcludedMesh(mesh);
  87078. };
  87079. /**
  87080. * Dispose the highlight layer and free resources.
  87081. */
  87082. HighlightLayer.prototype.dispose = function () {
  87083. if (this._meshes) {
  87084. // Clean mesh references
  87085. for (var id in this._meshes) {
  87086. var meshHighlight = this._meshes[id];
  87087. if (meshHighlight && meshHighlight.mesh) {
  87088. if (meshHighlight.observerHighlight) {
  87089. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87090. }
  87091. if (meshHighlight.observerDefault) {
  87092. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87093. }
  87094. }
  87095. }
  87096. this._meshes = null;
  87097. }
  87098. if (this._excludedMeshes) {
  87099. for (var id in this._excludedMeshes) {
  87100. var meshHighlight = this._excludedMeshes[id];
  87101. if (meshHighlight) {
  87102. if (meshHighlight.beforeRender) {
  87103. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87104. }
  87105. if (meshHighlight.afterRender) {
  87106. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87107. }
  87108. }
  87109. }
  87110. this._excludedMeshes = null;
  87111. }
  87112. _super.prototype.dispose.call(this);
  87113. };
  87114. /**
  87115. * Effect Name of the highlight layer.
  87116. */
  87117. HighlightLayer.EffectName = "HighlightLayer";
  87118. /**
  87119. * The neutral color used during the preparation of the glow effect.
  87120. * This is black by default as the blend operation is a blend operation.
  87121. */
  87122. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87123. /**
  87124. * Stencil value used for glowing meshes.
  87125. */
  87126. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87127. /**
  87128. * Stencil value used for the other meshes in the scene.
  87129. */
  87130. HighlightLayer.NormalMeshStencilReference = 0x01;
  87131. return HighlightLayer;
  87132. }(BABYLON.EffectLayer));
  87133. BABYLON.HighlightLayer = HighlightLayer;
  87134. })(BABYLON || (BABYLON = {}));
  87135. //# sourceMappingURL=babylon.highlightLayer.js.map
  87136. "use strict";
  87137. var BABYLON;
  87138. (function (BABYLON) {
  87139. /**
  87140. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87141. *
  87142. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87143. * glowy meshes to your scene.
  87144. *
  87145. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87146. */
  87147. var GlowLayer = /** @class */ (function (_super) {
  87148. __extends(GlowLayer, _super);
  87149. /**
  87150. * Instantiates a new glow Layer and references it to the scene.
  87151. * @param name The name of the layer
  87152. * @param scene The scene to use the layer in
  87153. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87154. */
  87155. function GlowLayer(name, scene, options) {
  87156. var _this = _super.call(this, name, scene) || this;
  87157. _this.name = name;
  87158. _this._intensity = 1.0;
  87159. _this._includedOnlyMeshes = [];
  87160. _this._excludedMeshes = [];
  87161. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87162. // Adapt options
  87163. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87164. // Initialize the layer
  87165. _this._init({
  87166. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87167. camera: _this._options.camera,
  87168. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87169. mainTextureRatio: _this._options.mainTextureRatio
  87170. });
  87171. return _this;
  87172. }
  87173. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87174. /**
  87175. * Gets the kernel size of the blur.
  87176. */
  87177. get: function () {
  87178. return this._horizontalBlurPostprocess1.kernel;
  87179. },
  87180. /**
  87181. * Sets the kernel size of the blur.
  87182. */
  87183. set: function (value) {
  87184. this._horizontalBlurPostprocess1.kernel = value;
  87185. this._verticalBlurPostprocess1.kernel = value;
  87186. this._horizontalBlurPostprocess2.kernel = value;
  87187. this._verticalBlurPostprocess2.kernel = value;
  87188. },
  87189. enumerable: true,
  87190. configurable: true
  87191. });
  87192. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87193. /**
  87194. * Gets the glow intensity.
  87195. */
  87196. get: function () {
  87197. return this._intensity;
  87198. },
  87199. /**
  87200. * Sets the glow intensity.
  87201. */
  87202. set: function (value) {
  87203. this._intensity = value;
  87204. },
  87205. enumerable: true,
  87206. configurable: true
  87207. });
  87208. /**
  87209. * Get the effect name of the layer.
  87210. * @return The effect name
  87211. */
  87212. GlowLayer.prototype.getEffectName = function () {
  87213. return GlowLayer.EffectName;
  87214. };
  87215. /**
  87216. * Create the merge effect. This is the shader use to blit the information back
  87217. * to the main canvas at the end of the scene rendering.
  87218. */
  87219. GlowLayer.prototype._createMergeEffect = function () {
  87220. // Effect
  87221. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87222. };
  87223. /**
  87224. * Creates the render target textures and post processes used in the glow layer.
  87225. */
  87226. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87227. var _this = this;
  87228. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87229. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87230. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87231. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87232. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87233. width: blurTextureWidth,
  87234. height: blurTextureHeight
  87235. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87236. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87237. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87238. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87239. this._blurTexture1.renderParticles = false;
  87240. this._blurTexture1.ignoreCameraViewport = true;
  87241. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87242. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87243. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87244. width: blurTextureWidth2,
  87245. height: blurTextureHeight2
  87246. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87247. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87248. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87249. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87250. this._blurTexture2.renderParticles = false;
  87251. this._blurTexture2.ignoreCameraViewport = true;
  87252. this._textures = [this._blurTexture1, this._blurTexture2];
  87253. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87254. width: blurTextureWidth,
  87255. height: blurTextureHeight
  87256. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87257. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87258. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87259. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87260. effect.setTexture("textureSampler", _this._mainTexture);
  87261. });
  87262. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87263. width: blurTextureWidth,
  87264. height: blurTextureHeight
  87265. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87266. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87267. width: blurTextureWidth2,
  87268. height: blurTextureHeight2
  87269. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87270. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87271. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87272. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87273. effect.setTexture("textureSampler", _this._blurTexture1);
  87274. });
  87275. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87276. width: blurTextureWidth2,
  87277. height: blurTextureHeight2
  87278. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87279. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87280. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87281. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87282. this._mainTexture.samples = this._options.mainTextureSamples;
  87283. this._mainTexture.onAfterUnbindObservable.add(function () {
  87284. var internalTexture = _this._blurTexture1.getInternalTexture();
  87285. if (internalTexture) {
  87286. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87287. internalTexture = _this._blurTexture2.getInternalTexture();
  87288. if (internalTexture) {
  87289. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87290. }
  87291. }
  87292. });
  87293. // Prevent autoClear.
  87294. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87295. };
  87296. /**
  87297. * Checks for the readiness of the element composing the layer.
  87298. * @param subMesh the mesh to check for
  87299. * @param useInstances specify wether or not to use instances to render the mesh
  87300. * @param emissiveTexture the associated emissive texture used to generate the glow
  87301. * @return true if ready otherwise, false
  87302. */
  87303. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87304. var material = subMesh.getMaterial();
  87305. var mesh = subMesh.getRenderingMesh();
  87306. if (!material || !mesh) {
  87307. return false;
  87308. }
  87309. var emissiveTexture = material.emissiveTexture;
  87310. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87311. };
  87312. /**
  87313. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87314. */
  87315. GlowLayer.prototype.needStencil = function () {
  87316. return false;
  87317. };
  87318. /**
  87319. * Implementation specific of rendering the generating effect on the main canvas.
  87320. * @param effect The effect used to render through
  87321. */
  87322. GlowLayer.prototype._internalRender = function (effect) {
  87323. // Texture
  87324. effect.setTexture("textureSampler", this._blurTexture1);
  87325. effect.setTexture("textureSampler2", this._blurTexture2);
  87326. effect.setFloat("offset", this._intensity);
  87327. // Cache
  87328. var engine = this._engine;
  87329. var previousStencilBuffer = engine.getStencilBuffer();
  87330. // Draw order
  87331. engine.setStencilBuffer(false);
  87332. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87333. // Draw order
  87334. engine.setStencilBuffer(previousStencilBuffer);
  87335. };
  87336. /**
  87337. * Sets the required values for both the emissive texture and and the main color.
  87338. */
  87339. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87340. var textureLevel = 1.0;
  87341. if (this.customEmissiveTextureSelector) {
  87342. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87343. }
  87344. else {
  87345. if (material) {
  87346. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87347. if (this._emissiveTextureAndColor.texture) {
  87348. textureLevel = this._emissiveTextureAndColor.texture.level;
  87349. }
  87350. }
  87351. else {
  87352. this._emissiveTextureAndColor.texture = null;
  87353. }
  87354. }
  87355. if (this.customEmissiveColorSelector) {
  87356. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87357. }
  87358. else {
  87359. if (material.emissiveColor) {
  87360. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87361. }
  87362. else {
  87363. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87364. }
  87365. }
  87366. };
  87367. /**
  87368. * Returns true if the mesh should render, otherwise false.
  87369. * @param mesh The mesh to render
  87370. * @returns true if it should render otherwise false
  87371. */
  87372. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87373. return this.hasMesh(mesh);
  87374. };
  87375. /**
  87376. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87377. * @param mesh The mesh to exclude from the glow layer
  87378. */
  87379. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87380. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87381. this._excludedMeshes.push(mesh.uniqueId);
  87382. }
  87383. };
  87384. /**
  87385. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87386. * @param mesh The mesh to remove
  87387. */
  87388. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87389. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87390. if (index !== -1) {
  87391. this._excludedMeshes.splice(index, 1);
  87392. }
  87393. };
  87394. /**
  87395. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87396. * @param mesh The mesh to include in the glow layer
  87397. */
  87398. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87399. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87400. this._includedOnlyMeshes.push(mesh.uniqueId);
  87401. }
  87402. };
  87403. /**
  87404. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87405. * @param mesh The mesh to remove
  87406. */
  87407. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87408. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87409. if (index !== -1) {
  87410. this._includedOnlyMeshes.splice(index, 1);
  87411. }
  87412. };
  87413. /**
  87414. * Determine if a given mesh will be used in the glow layer
  87415. * @param mesh The mesh to test
  87416. * @returns true if the mesh will be highlighted by the current glow layer
  87417. */
  87418. GlowLayer.prototype.hasMesh = function (mesh) {
  87419. // Included Mesh
  87420. if (this._includedOnlyMeshes.length) {
  87421. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87422. }
  87423. ;
  87424. // Excluded Mesh
  87425. if (this._excludedMeshes.length) {
  87426. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87427. }
  87428. ;
  87429. return true;
  87430. };
  87431. /**
  87432. * Free any resources and references associated to a mesh.
  87433. * Internal use
  87434. * @param mesh The mesh to free.
  87435. */
  87436. GlowLayer.prototype._disposeMesh = function (mesh) {
  87437. this.removeIncludedOnlyMesh(mesh);
  87438. this.removeExcludedMesh(mesh);
  87439. };
  87440. /**
  87441. * Effect Name of the layer.
  87442. */
  87443. GlowLayer.EffectName = "GlowLayer";
  87444. /**
  87445. * The default blur kernel size used for the glow.
  87446. */
  87447. GlowLayer.DefaultBlurKernelSize = 32;
  87448. /**
  87449. * The default texture size ratio used for the glow.
  87450. */
  87451. GlowLayer.DefaultTextureRatio = 0.5;
  87452. return GlowLayer;
  87453. }(BABYLON.EffectLayer));
  87454. BABYLON.GlowLayer = GlowLayer;
  87455. })(BABYLON || (BABYLON = {}));
  87456. //# sourceMappingURL=babylon.glowLayer.js.map
  87457. "use strict";
  87458. var BABYLON;
  87459. (function (BABYLON) {
  87460. /**
  87461. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87462. */
  87463. var AssetTaskState;
  87464. (function (AssetTaskState) {
  87465. /**
  87466. * Initialization
  87467. */
  87468. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87469. /**
  87470. * Running
  87471. */
  87472. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87473. /**
  87474. * Done
  87475. */
  87476. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87477. /**
  87478. * Error
  87479. */
  87480. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87481. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87482. /**
  87483. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87484. */
  87485. var AbstractAssetTask = /** @class */ (function () {
  87486. /**
  87487. * Creates a new {BABYLON.AssetsManager}
  87488. * @param name defines the name of the task
  87489. */
  87490. function AbstractAssetTask(
  87491. /**
  87492. * Task name
  87493. */ name) {
  87494. this.name = name;
  87495. this._isCompleted = false;
  87496. this._taskState = AssetTaskState.INIT;
  87497. }
  87498. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87499. /**
  87500. * Get if the task is completed
  87501. */
  87502. get: function () {
  87503. return this._isCompleted;
  87504. },
  87505. enumerable: true,
  87506. configurable: true
  87507. });
  87508. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87509. /**
  87510. * Gets the current state of the task
  87511. */
  87512. get: function () {
  87513. return this._taskState;
  87514. },
  87515. enumerable: true,
  87516. configurable: true
  87517. });
  87518. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87519. /**
  87520. * Gets the current error object (if task is in error)
  87521. */
  87522. get: function () {
  87523. return this._errorObject;
  87524. },
  87525. enumerable: true,
  87526. configurable: true
  87527. });
  87528. /**
  87529. * Internal only
  87530. * @ignore
  87531. */
  87532. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87533. if (this._errorObject) {
  87534. return;
  87535. }
  87536. this._errorObject = {
  87537. message: message,
  87538. exception: exception
  87539. };
  87540. };
  87541. /**
  87542. * Execute the current task
  87543. * @param scene defines the scene where you want your assets to be loaded
  87544. * @param onSuccess is a callback called when the task is successfully executed
  87545. * @param onError is a callback called if an error occurs
  87546. */
  87547. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87548. var _this = this;
  87549. this._taskState = AssetTaskState.RUNNING;
  87550. this.runTask(scene, function () {
  87551. _this.onDoneCallback(onSuccess, onError);
  87552. }, function (msg, exception) {
  87553. _this.onErrorCallback(onError, msg, exception);
  87554. });
  87555. };
  87556. /**
  87557. * Execute the current task
  87558. * @param scene defines the scene where you want your assets to be loaded
  87559. * @param onSuccess is a callback called when the task is successfully executed
  87560. * @param onError is a callback called if an error occurs
  87561. */
  87562. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87563. throw new Error("runTask is not implemented");
  87564. };
  87565. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87566. this._taskState = AssetTaskState.ERROR;
  87567. this._errorObject = {
  87568. message: message,
  87569. exception: exception
  87570. };
  87571. if (this.onError) {
  87572. this.onError(this, message, exception);
  87573. }
  87574. onError();
  87575. };
  87576. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87577. try {
  87578. this._taskState = AssetTaskState.DONE;
  87579. this._isCompleted = true;
  87580. if (this.onSuccess) {
  87581. this.onSuccess(this);
  87582. }
  87583. onSuccess();
  87584. }
  87585. catch (e) {
  87586. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87587. }
  87588. };
  87589. return AbstractAssetTask;
  87590. }());
  87591. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87592. /**
  87593. * Class used to share progress information about assets loading
  87594. */
  87595. var AssetsProgressEvent = /** @class */ (function () {
  87596. /**
  87597. * Creates a {BABYLON.AssetsProgressEvent}
  87598. * @param remainingCount defines the number of remaining tasks to process
  87599. * @param totalCount defines the total number of tasks
  87600. * @param task defines the task that was just processed
  87601. */
  87602. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87603. this.remainingCount = remainingCount;
  87604. this.totalCount = totalCount;
  87605. this.task = task;
  87606. }
  87607. return AssetsProgressEvent;
  87608. }());
  87609. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87610. /**
  87611. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87612. */
  87613. var MeshAssetTask = /** @class */ (function (_super) {
  87614. __extends(MeshAssetTask, _super);
  87615. /**
  87616. * Creates a new {BABYLON.MeshAssetTask}
  87617. * @param name defines the name of the task
  87618. * @param meshesNames defines the list of mesh's names you want to load
  87619. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87620. * @param sceneFilename defines the filename of the scene to load from
  87621. */
  87622. function MeshAssetTask(
  87623. /**
  87624. * Defines the name of the task
  87625. */
  87626. name,
  87627. /**
  87628. * Defines the list of mesh's names you want to load
  87629. */
  87630. meshesNames,
  87631. /**
  87632. * Defines the root url to use as a base to load your meshes and associated resources
  87633. */
  87634. rootUrl,
  87635. /**
  87636. * Defines the filename of the scene to load from
  87637. */
  87638. sceneFilename) {
  87639. var _this = _super.call(this, name) || this;
  87640. _this.name = name;
  87641. _this.meshesNames = meshesNames;
  87642. _this.rootUrl = rootUrl;
  87643. _this.sceneFilename = sceneFilename;
  87644. return _this;
  87645. }
  87646. /**
  87647. * Execute the current task
  87648. * @param scene defines the scene where you want your assets to be loaded
  87649. * @param onSuccess is a callback called when the task is successfully executed
  87650. * @param onError is a callback called if an error occurs
  87651. */
  87652. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87653. var _this = this;
  87654. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87655. _this.loadedMeshes = meshes;
  87656. _this.loadedParticleSystems = particleSystems;
  87657. _this.loadedSkeletons = skeletons;
  87658. onSuccess();
  87659. }, null, function (scene, message, exception) {
  87660. onError(message, exception);
  87661. });
  87662. };
  87663. return MeshAssetTask;
  87664. }(AbstractAssetTask));
  87665. BABYLON.MeshAssetTask = MeshAssetTask;
  87666. /**
  87667. * Define a task used by {BABYLON.AssetsManager} to load text content
  87668. */
  87669. var TextFileAssetTask = /** @class */ (function (_super) {
  87670. __extends(TextFileAssetTask, _super);
  87671. /**
  87672. * Creates a new TextFileAssetTask object
  87673. * @param name defines the name of the task
  87674. * @param url defines the location of the file to load
  87675. */
  87676. function TextFileAssetTask(
  87677. /**
  87678. * Defines the name of the task
  87679. */
  87680. name,
  87681. /**
  87682. * Defines the location of the file to load
  87683. */
  87684. url) {
  87685. var _this = _super.call(this, name) || this;
  87686. _this.name = name;
  87687. _this.url = url;
  87688. return _this;
  87689. }
  87690. /**
  87691. * Execute the current task
  87692. * @param scene defines the scene where you want your assets to be loaded
  87693. * @param onSuccess is a callback called when the task is successfully executed
  87694. * @param onError is a callback called if an error occurs
  87695. */
  87696. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87697. var _this = this;
  87698. scene._loadFile(this.url, function (data) {
  87699. _this.text = data;
  87700. onSuccess();
  87701. }, undefined, false, false, function (request, exception) {
  87702. if (request) {
  87703. onError(request.status + " " + request.statusText, exception);
  87704. }
  87705. });
  87706. };
  87707. return TextFileAssetTask;
  87708. }(AbstractAssetTask));
  87709. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87710. /**
  87711. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87712. */
  87713. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87714. __extends(BinaryFileAssetTask, _super);
  87715. /**
  87716. * Creates a new BinaryFileAssetTask object
  87717. * @param name defines the name of the new task
  87718. * @param url defines the location of the file to load
  87719. */
  87720. function BinaryFileAssetTask(
  87721. /**
  87722. * Defines the name of the task
  87723. */
  87724. name,
  87725. /**
  87726. * Defines the location of the file to load
  87727. */
  87728. url) {
  87729. var _this = _super.call(this, name) || this;
  87730. _this.name = name;
  87731. _this.url = url;
  87732. return _this;
  87733. }
  87734. /**
  87735. * Execute the current task
  87736. * @param scene defines the scene where you want your assets to be loaded
  87737. * @param onSuccess is a callback called when the task is successfully executed
  87738. * @param onError is a callback called if an error occurs
  87739. */
  87740. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87741. var _this = this;
  87742. scene._loadFile(this.url, function (data) {
  87743. _this.data = data;
  87744. onSuccess();
  87745. }, undefined, true, true, function (request, exception) {
  87746. if (request) {
  87747. onError(request.status + " " + request.statusText, exception);
  87748. }
  87749. });
  87750. };
  87751. return BinaryFileAssetTask;
  87752. }(AbstractAssetTask));
  87753. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  87754. /**
  87755. * Define a task used by {BABYLON.AssetsManager} to load images
  87756. */
  87757. var ImageAssetTask = /** @class */ (function (_super) {
  87758. __extends(ImageAssetTask, _super);
  87759. /**
  87760. * Creates a new ImageAssetTask
  87761. * @param name defines the name of the task
  87762. * @param url defines the location of the image to load
  87763. */
  87764. function ImageAssetTask(
  87765. /**
  87766. * Defines the name of the task
  87767. */
  87768. name,
  87769. /**
  87770. * Defines the location of the image to load
  87771. */
  87772. url) {
  87773. var _this = _super.call(this, name) || this;
  87774. _this.name = name;
  87775. _this.url = url;
  87776. return _this;
  87777. }
  87778. /**
  87779. * Execute the current task
  87780. * @param scene defines the scene where you want your assets to be loaded
  87781. * @param onSuccess is a callback called when the task is successfully executed
  87782. * @param onError is a callback called if an error occurs
  87783. */
  87784. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87785. var _this = this;
  87786. var img = new Image();
  87787. BABYLON.Tools.SetCorsBehavior(this.url, img);
  87788. img.onload = function () {
  87789. _this.image = img;
  87790. onSuccess();
  87791. };
  87792. img.onerror = function (err) {
  87793. onError("Error loading image", err);
  87794. };
  87795. img.src = this.url;
  87796. };
  87797. return ImageAssetTask;
  87798. }(AbstractAssetTask));
  87799. BABYLON.ImageAssetTask = ImageAssetTask;
  87800. /**
  87801. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87802. */
  87803. var TextureAssetTask = /** @class */ (function (_super) {
  87804. __extends(TextureAssetTask, _super);
  87805. /**
  87806. * Creates a new TextureAssetTask object
  87807. * @param name defines the name of the task
  87808. * @param url defines the location of the file to load
  87809. * @param noMipmap defines if mipmap should not be generated (default is false)
  87810. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87811. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87812. */
  87813. function TextureAssetTask(
  87814. /**
  87815. * Defines the name of the task
  87816. */
  87817. name,
  87818. /**
  87819. * Defines the location of the file to load
  87820. */
  87821. url,
  87822. /**
  87823. * Defines if mipmap should not be generated (default is false)
  87824. */
  87825. noMipmap,
  87826. /**
  87827. * Defines if texture must be inverted on Y axis (default is false)
  87828. */
  87829. invertY,
  87830. /**
  87831. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87832. */
  87833. samplingMode) {
  87834. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87835. var _this = _super.call(this, name) || this;
  87836. _this.name = name;
  87837. _this.url = url;
  87838. _this.noMipmap = noMipmap;
  87839. _this.invertY = invertY;
  87840. _this.samplingMode = samplingMode;
  87841. return _this;
  87842. }
  87843. /**
  87844. * Execute the current task
  87845. * @param scene defines the scene where you want your assets to be loaded
  87846. * @param onSuccess is a callback called when the task is successfully executed
  87847. * @param onError is a callback called if an error occurs
  87848. */
  87849. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87850. var onload = function () {
  87851. onSuccess();
  87852. };
  87853. var onerror = function (message, exception) {
  87854. onError(message, exception);
  87855. };
  87856. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87857. };
  87858. return TextureAssetTask;
  87859. }(AbstractAssetTask));
  87860. BABYLON.TextureAssetTask = TextureAssetTask;
  87861. /**
  87862. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87863. */
  87864. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87865. __extends(CubeTextureAssetTask, _super);
  87866. /**
  87867. * Creates a new CubeTextureAssetTask
  87868. * @param name defines the name of the task
  87869. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87870. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87871. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87872. * @param files defines the explicit list of files (undefined by default)
  87873. */
  87874. function CubeTextureAssetTask(
  87875. /**
  87876. * Defines the name of the task
  87877. */
  87878. name,
  87879. /**
  87880. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87881. */
  87882. url,
  87883. /**
  87884. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87885. */
  87886. extensions,
  87887. /**
  87888. * Defines if mipmaps should not be generated (default is false)
  87889. */
  87890. noMipmap,
  87891. /**
  87892. * Defines the explicit list of files (undefined by default)
  87893. */
  87894. files) {
  87895. var _this = _super.call(this, name) || this;
  87896. _this.name = name;
  87897. _this.url = url;
  87898. _this.extensions = extensions;
  87899. _this.noMipmap = noMipmap;
  87900. _this.files = files;
  87901. return _this;
  87902. }
  87903. /**
  87904. * Execute the current task
  87905. * @param scene defines the scene where you want your assets to be loaded
  87906. * @param onSuccess is a callback called when the task is successfully executed
  87907. * @param onError is a callback called if an error occurs
  87908. */
  87909. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87910. var onload = function () {
  87911. onSuccess();
  87912. };
  87913. var onerror = function (message, exception) {
  87914. onError(message, exception);
  87915. };
  87916. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87917. };
  87918. return CubeTextureAssetTask;
  87919. }(AbstractAssetTask));
  87920. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87921. /**
  87922. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87923. */
  87924. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87925. __extends(HDRCubeTextureAssetTask, _super);
  87926. /**
  87927. * Creates a new HDRCubeTextureAssetTask object
  87928. * @param name defines the name of the task
  87929. * @param url defines the location of the file to load
  87930. * @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.
  87931. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87932. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87933. * @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)
  87934. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87935. */
  87936. function HDRCubeTextureAssetTask(
  87937. /**
  87938. * Defines the name of the task
  87939. */
  87940. name,
  87941. /**
  87942. * Defines the location of the file to load
  87943. */
  87944. url,
  87945. /**
  87946. * 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.
  87947. */
  87948. size,
  87949. /**
  87950. * Defines if mipmaps should not be generated (default is false)
  87951. */
  87952. noMipmap,
  87953. /**
  87954. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87955. */
  87956. generateHarmonics,
  87957. /**
  87958. * 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)
  87959. */
  87960. useInGammaSpace,
  87961. /**
  87962. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87963. */
  87964. usePMREMGenerator) {
  87965. if (noMipmap === void 0) { noMipmap = false; }
  87966. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87967. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87968. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87969. var _this = _super.call(this, name) || this;
  87970. _this.name = name;
  87971. _this.url = url;
  87972. _this.size = size;
  87973. _this.noMipmap = noMipmap;
  87974. _this.generateHarmonics = generateHarmonics;
  87975. _this.useInGammaSpace = useInGammaSpace;
  87976. _this.usePMREMGenerator = usePMREMGenerator;
  87977. return _this;
  87978. }
  87979. /**
  87980. * Execute the current task
  87981. * @param scene defines the scene where you want your assets to be loaded
  87982. * @param onSuccess is a callback called when the task is successfully executed
  87983. * @param onError is a callback called if an error occurs
  87984. */
  87985. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87986. var onload = function () {
  87987. onSuccess();
  87988. };
  87989. var onerror = function (message, exception) {
  87990. onError(message, exception);
  87991. };
  87992. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87993. };
  87994. return HDRCubeTextureAssetTask;
  87995. }(AbstractAssetTask));
  87996. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87997. /**
  87998. * This class can be used to easily import assets into a scene
  87999. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  88000. */
  88001. var AssetsManager = /** @class */ (function () {
  88002. /**
  88003. * Creates a new AssetsManager
  88004. * @param scene defines the scene to work on
  88005. */
  88006. function AssetsManager(scene) {
  88007. this._isLoading = false;
  88008. this._tasks = new Array();
  88009. this._waitingTasksCount = 0;
  88010. this._totalTasksCount = 0;
  88011. /**
  88012. * Observable called when all tasks are processed
  88013. */
  88014. this.onTaskSuccessObservable = new BABYLON.Observable();
  88015. /**
  88016. * Observable called when a task had an error
  88017. */
  88018. this.onTaskErrorObservable = new BABYLON.Observable();
  88019. /**
  88020. * Observable called when a task is successful
  88021. */
  88022. this.onTasksDoneObservable = new BABYLON.Observable();
  88023. /**
  88024. * Observable called when a task is done (whatever the result is)
  88025. */
  88026. this.onProgressObservable = new BABYLON.Observable();
  88027. /**
  88028. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  88029. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  88030. */
  88031. this.useDefaultLoadingScreen = true;
  88032. this._scene = scene;
  88033. }
  88034. /**
  88035. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88036. * @param taskName defines the name of the new task
  88037. * @param meshesNames defines the name of meshes to load
  88038. * @param rootUrl defines the root url to use to locate files
  88039. * @param sceneFilename defines the filename of the scene file
  88040. * @returns a new {BABYLON.MeshAssetTask} object
  88041. */
  88042. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88043. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88044. this._tasks.push(task);
  88045. return task;
  88046. };
  88047. /**
  88048. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88049. * @param taskName defines the name of the new task
  88050. * @param url defines the url of the file to load
  88051. * @returns a new {BABYLON.TextFileAssetTask} object
  88052. */
  88053. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88054. var task = new TextFileAssetTask(taskName, url);
  88055. this._tasks.push(task);
  88056. return task;
  88057. };
  88058. /**
  88059. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88060. * @param taskName defines the name of the new task
  88061. * @param url defines the url of the file to load
  88062. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88063. */
  88064. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88065. var task = new BinaryFileAssetTask(taskName, url);
  88066. this._tasks.push(task);
  88067. return task;
  88068. };
  88069. /**
  88070. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88071. * @param taskName defines the name of the new task
  88072. * @param url defines the url of the file to load
  88073. * @returns a new {BABYLON.ImageAssetTask} object
  88074. */
  88075. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88076. var task = new ImageAssetTask(taskName, url);
  88077. this._tasks.push(task);
  88078. return task;
  88079. };
  88080. /**
  88081. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88082. * @param taskName defines the name of the new task
  88083. * @param url defines the url of the file to load
  88084. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88085. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88086. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88087. * @returns a new {BABYLON.TextureAssetTask} object
  88088. */
  88089. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88090. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88091. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88092. this._tasks.push(task);
  88093. return task;
  88094. };
  88095. /**
  88096. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88097. * @param taskName defines the name of the new task
  88098. * @param url defines the url of the file to load
  88099. * @param extensions defines the extension to use to load the cube map (can be null)
  88100. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88101. * @param files defines the list of files to load (can be null)
  88102. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88103. */
  88104. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88105. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88106. this._tasks.push(task);
  88107. return task;
  88108. };
  88109. /**
  88110. *
  88111. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88112. * @param taskName defines the name of the new task
  88113. * @param url defines the url of the file to load
  88114. * @param size defines the size you want for the cubemap (can be null)
  88115. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88116. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88117. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88118. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88119. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88120. */
  88121. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88122. if (noMipmap === void 0) { noMipmap = false; }
  88123. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88124. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88125. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88126. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88127. this._tasks.push(task);
  88128. return task;
  88129. };
  88130. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88131. var _this = this;
  88132. this._waitingTasksCount--;
  88133. try {
  88134. if (task.taskState === AssetTaskState.DONE) {
  88135. // Let's remove successfull tasks
  88136. BABYLON.Tools.SetImmediate(function () {
  88137. var index = _this._tasks.indexOf(task);
  88138. if (index > -1) {
  88139. _this._tasks.splice(index, 1);
  88140. }
  88141. });
  88142. }
  88143. if (this.onProgress) {
  88144. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88145. }
  88146. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88147. }
  88148. catch (e) {
  88149. BABYLON.Tools.Error("Error running progress callbacks.");
  88150. console.log(e);
  88151. }
  88152. if (this._waitingTasksCount === 0) {
  88153. try {
  88154. if (this.onFinish) {
  88155. this.onFinish(this._tasks);
  88156. }
  88157. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88158. }
  88159. catch (e) {
  88160. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88161. console.log(e);
  88162. }
  88163. this._isLoading = false;
  88164. this._scene.getEngine().hideLoadingUI();
  88165. }
  88166. };
  88167. AssetsManager.prototype._runTask = function (task) {
  88168. var _this = this;
  88169. var done = function () {
  88170. try {
  88171. if (_this.onTaskSuccess) {
  88172. _this.onTaskSuccess(task);
  88173. }
  88174. _this.onTaskSuccessObservable.notifyObservers(task);
  88175. _this._decreaseWaitingTasksCount(task);
  88176. }
  88177. catch (e) {
  88178. error("Error executing task success callbacks", e);
  88179. }
  88180. };
  88181. var error = function (message, exception) {
  88182. task._setErrorObject(message, exception);
  88183. if (_this.onTaskError) {
  88184. _this.onTaskError(task);
  88185. }
  88186. _this.onTaskErrorObservable.notifyObservers(task);
  88187. _this._decreaseWaitingTasksCount(task);
  88188. };
  88189. task.run(this._scene, done, error);
  88190. };
  88191. /**
  88192. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88193. * @return the current instance of the {BABYLON.AssetsManager}
  88194. */
  88195. AssetsManager.prototype.reset = function () {
  88196. this._isLoading = false;
  88197. this._tasks = new Array();
  88198. return this;
  88199. };
  88200. /**
  88201. * Start the loading process
  88202. * @return the current instance of the {BABYLON.AssetsManager}
  88203. */
  88204. AssetsManager.prototype.load = function () {
  88205. if (this._isLoading) {
  88206. return this;
  88207. }
  88208. this._isLoading = true;
  88209. this._waitingTasksCount = this._tasks.length;
  88210. this._totalTasksCount = this._tasks.length;
  88211. if (this._waitingTasksCount === 0) {
  88212. this._isLoading = false;
  88213. if (this.onFinish) {
  88214. this.onFinish(this._tasks);
  88215. }
  88216. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88217. return this;
  88218. }
  88219. if (this.useDefaultLoadingScreen) {
  88220. this._scene.getEngine().displayLoadingUI();
  88221. }
  88222. for (var index = 0; index < this._tasks.length; index++) {
  88223. var task = this._tasks[index];
  88224. this._runTask(task);
  88225. }
  88226. return this;
  88227. };
  88228. return AssetsManager;
  88229. }());
  88230. BABYLON.AssetsManager = AssetsManager;
  88231. })(BABYLON || (BABYLON = {}));
  88232. //# sourceMappingURL=babylon.assetsManager.js.map
  88233. "use strict";
  88234. var BABYLON;
  88235. (function (BABYLON) {
  88236. var serializedGeometries = [];
  88237. var serializeGeometry = function (geometry, serializationGeometries) {
  88238. if (serializedGeometries[geometry.id]) {
  88239. return;
  88240. }
  88241. if (geometry.doNotSerialize) {
  88242. return;
  88243. }
  88244. if (geometry instanceof BABYLON.BoxGeometry) {
  88245. serializationGeometries.boxes.push(geometry.serialize());
  88246. }
  88247. else if (geometry instanceof BABYLON.SphereGeometry) {
  88248. serializationGeometries.spheres.push(geometry.serialize());
  88249. }
  88250. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88251. serializationGeometries.cylinders.push(geometry.serialize());
  88252. }
  88253. else if (geometry instanceof BABYLON.TorusGeometry) {
  88254. serializationGeometries.toruses.push(geometry.serialize());
  88255. }
  88256. else if (geometry instanceof BABYLON.GroundGeometry) {
  88257. serializationGeometries.grounds.push(geometry.serialize());
  88258. }
  88259. else if (geometry instanceof BABYLON.Plane) {
  88260. serializationGeometries.planes.push(geometry.serialize());
  88261. }
  88262. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88263. serializationGeometries.torusKnots.push(geometry.serialize());
  88264. }
  88265. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88266. throw new Error("Unknown primitive type");
  88267. }
  88268. else {
  88269. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88270. }
  88271. serializedGeometries[geometry.id] = true;
  88272. };
  88273. var serializeMesh = function (mesh, serializationScene) {
  88274. var serializationObject = {};
  88275. // Geometry
  88276. var geometry = mesh._geometry;
  88277. if (geometry) {
  88278. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88279. // 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
  88280. serializeGeometry(geometry, serializationScene.geometries);
  88281. }
  88282. }
  88283. // Custom
  88284. if (mesh.serialize) {
  88285. mesh.serialize(serializationObject);
  88286. }
  88287. return serializationObject;
  88288. };
  88289. var finalizeSingleMesh = function (mesh, serializationObject) {
  88290. //only works if the mesh is already loaded
  88291. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88292. //serialize material
  88293. if (mesh.material) {
  88294. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88295. serializationObject.materials = serializationObject.materials || [];
  88296. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88297. serializationObject.materials.push(mesh.material.serialize());
  88298. }
  88299. }
  88300. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88301. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88302. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88303. serializationObject.multiMaterials.push(mesh.material.serialize());
  88304. }
  88305. }
  88306. }
  88307. //serialize geometry
  88308. var geometry = mesh._geometry;
  88309. if (geometry) {
  88310. if (!serializationObject.geometries) {
  88311. serializationObject.geometries = {};
  88312. serializationObject.geometries.boxes = [];
  88313. serializationObject.geometries.spheres = [];
  88314. serializationObject.geometries.cylinders = [];
  88315. serializationObject.geometries.toruses = [];
  88316. serializationObject.geometries.grounds = [];
  88317. serializationObject.geometries.planes = [];
  88318. serializationObject.geometries.torusKnots = [];
  88319. serializationObject.geometries.vertexData = [];
  88320. }
  88321. serializeGeometry(geometry, serializationObject.geometries);
  88322. }
  88323. // Skeletons
  88324. if (mesh.skeleton) {
  88325. serializationObject.skeletons = serializationObject.skeletons || [];
  88326. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88327. }
  88328. //serialize the actual mesh
  88329. serializationObject.meshes = serializationObject.meshes || [];
  88330. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88331. }
  88332. };
  88333. var SceneSerializer = /** @class */ (function () {
  88334. function SceneSerializer() {
  88335. }
  88336. SceneSerializer.ClearCache = function () {
  88337. serializedGeometries = [];
  88338. };
  88339. SceneSerializer.Serialize = function (scene) {
  88340. var serializationObject = {};
  88341. SceneSerializer.ClearCache();
  88342. // Scene
  88343. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88344. serializationObject.autoClear = scene.autoClear;
  88345. serializationObject.clearColor = scene.clearColor.asArray();
  88346. serializationObject.ambientColor = scene.ambientColor.asArray();
  88347. serializationObject.gravity = scene.gravity.asArray();
  88348. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88349. serializationObject.workerCollisions = scene.workerCollisions;
  88350. // Fog
  88351. if (scene.fogMode && scene.fogMode !== 0) {
  88352. serializationObject.fogMode = scene.fogMode;
  88353. serializationObject.fogColor = scene.fogColor.asArray();
  88354. serializationObject.fogStart = scene.fogStart;
  88355. serializationObject.fogEnd = scene.fogEnd;
  88356. serializationObject.fogDensity = scene.fogDensity;
  88357. }
  88358. //Physics
  88359. if (scene.isPhysicsEnabled()) {
  88360. var physicEngine = scene.getPhysicsEngine();
  88361. if (physicEngine) {
  88362. serializationObject.physicsEnabled = true;
  88363. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88364. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88365. }
  88366. }
  88367. // Metadata
  88368. if (scene.metadata) {
  88369. serializationObject.metadata = scene.metadata;
  88370. }
  88371. // Morph targets
  88372. serializationObject.morphTargetManagers = [];
  88373. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88374. var abstractMesh = _a[_i];
  88375. var manager = abstractMesh.morphTargetManager;
  88376. if (manager) {
  88377. serializationObject.morphTargetManagers.push(manager.serialize());
  88378. }
  88379. }
  88380. // Lights
  88381. serializationObject.lights = [];
  88382. var index;
  88383. var light;
  88384. for (index = 0; index < scene.lights.length; index++) {
  88385. light = scene.lights[index];
  88386. if (!light.doNotSerialize) {
  88387. serializationObject.lights.push(light.serialize());
  88388. }
  88389. }
  88390. // Cameras
  88391. serializationObject.cameras = [];
  88392. for (index = 0; index < scene.cameras.length; index++) {
  88393. var camera = scene.cameras[index];
  88394. if (!camera.doNotSerialize) {
  88395. serializationObject.cameras.push(camera.serialize());
  88396. }
  88397. }
  88398. if (scene.activeCamera) {
  88399. serializationObject.activeCameraID = scene.activeCamera.id;
  88400. }
  88401. // Animations
  88402. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88403. // Materials
  88404. serializationObject.materials = [];
  88405. serializationObject.multiMaterials = [];
  88406. var material;
  88407. for (index = 0; index < scene.materials.length; index++) {
  88408. material = scene.materials[index];
  88409. if (!material.doNotSerialize) {
  88410. serializationObject.materials.push(material.serialize());
  88411. }
  88412. }
  88413. // MultiMaterials
  88414. serializationObject.multiMaterials = [];
  88415. for (index = 0; index < scene.multiMaterials.length; index++) {
  88416. var multiMaterial = scene.multiMaterials[index];
  88417. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88418. }
  88419. // Environment texture
  88420. if (scene.environmentTexture) {
  88421. serializationObject.environmentTexture = scene.environmentTexture.name;
  88422. }
  88423. // Skeletons
  88424. serializationObject.skeletons = [];
  88425. for (index = 0; index < scene.skeletons.length; index++) {
  88426. var skeleton = scene.skeletons[index];
  88427. if (!skeleton.doNotSerialize) {
  88428. serializationObject.skeletons.push(skeleton.serialize());
  88429. }
  88430. }
  88431. // Transform nodes
  88432. serializationObject.transformNodes = [];
  88433. for (index = 0; index < scene.transformNodes.length; index++) {
  88434. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88435. }
  88436. // Geometries
  88437. serializationObject.geometries = {};
  88438. serializationObject.geometries.boxes = [];
  88439. serializationObject.geometries.spheres = [];
  88440. serializationObject.geometries.cylinders = [];
  88441. serializationObject.geometries.toruses = [];
  88442. serializationObject.geometries.grounds = [];
  88443. serializationObject.geometries.planes = [];
  88444. serializationObject.geometries.torusKnots = [];
  88445. serializationObject.geometries.vertexData = [];
  88446. serializedGeometries = [];
  88447. var geometries = scene.getGeometries();
  88448. for (index = 0; index < geometries.length; index++) {
  88449. var geometry = geometries[index];
  88450. if (geometry.isReady()) {
  88451. serializeGeometry(geometry, serializationObject.geometries);
  88452. }
  88453. }
  88454. // Meshes
  88455. serializationObject.meshes = [];
  88456. for (index = 0; index < scene.meshes.length; index++) {
  88457. var abstractMesh = scene.meshes[index];
  88458. if (abstractMesh instanceof BABYLON.Mesh) {
  88459. var mesh = abstractMesh;
  88460. if (!mesh.doNotSerialize) {
  88461. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88462. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88463. }
  88464. }
  88465. }
  88466. }
  88467. // Particles Systems
  88468. serializationObject.particleSystems = [];
  88469. for (index = 0; index < scene.particleSystems.length; index++) {
  88470. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88471. }
  88472. // Lens flares
  88473. serializationObject.lensFlareSystems = [];
  88474. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88475. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88476. }
  88477. // Shadows
  88478. serializationObject.shadowGenerators = [];
  88479. for (index = 0; index < scene.lights.length; index++) {
  88480. light = scene.lights[index];
  88481. var shadowGenerator = light.getShadowGenerator();
  88482. if (shadowGenerator) {
  88483. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88484. }
  88485. }
  88486. // Action Manager
  88487. if (scene.actionManager) {
  88488. serializationObject.actions = scene.actionManager.serialize("scene");
  88489. }
  88490. // Audio
  88491. serializationObject.sounds = [];
  88492. for (index = 0; index < scene.soundTracks.length; index++) {
  88493. var soundtrack = scene.soundTracks[index];
  88494. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88495. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88496. }
  88497. }
  88498. return serializationObject;
  88499. };
  88500. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88501. if (withParents === void 0) { withParents = false; }
  88502. if (withChildren === void 0) { withChildren = false; }
  88503. var serializationObject = {};
  88504. SceneSerializer.ClearCache();
  88505. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88506. if (withParents || withChildren) {
  88507. //deliberate for loop! not for each, appended should be processed as well.
  88508. for (var i = 0; i < toSerialize.length; ++i) {
  88509. if (withChildren) {
  88510. toSerialize[i].getDescendants().forEach(function (node) {
  88511. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88512. toSerialize.push(node);
  88513. }
  88514. });
  88515. }
  88516. //make sure the array doesn't contain the object already
  88517. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88518. toSerialize.push(toSerialize[i].parent);
  88519. }
  88520. }
  88521. }
  88522. toSerialize.forEach(function (mesh) {
  88523. finalizeSingleMesh(mesh, serializationObject);
  88524. });
  88525. return serializationObject;
  88526. };
  88527. return SceneSerializer;
  88528. }());
  88529. BABYLON.SceneSerializer = SceneSerializer;
  88530. })(BABYLON || (BABYLON = {}));
  88531. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88532. "use strict";
  88533. var BABYLON;
  88534. (function (BABYLON) {
  88535. var ReflectionProbe = /** @class */ (function () {
  88536. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88537. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88538. var _this = this;
  88539. this.name = name;
  88540. this._viewMatrix = BABYLON.Matrix.Identity();
  88541. this._target = BABYLON.Vector3.Zero();
  88542. this._add = BABYLON.Vector3.Zero();
  88543. this._invertYAxis = false;
  88544. this.position = BABYLON.Vector3.Zero();
  88545. this._scene = scene;
  88546. this._scene.reflectionProbes.push(this);
  88547. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88548. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88549. switch (faceIndex) {
  88550. case 0:
  88551. _this._add.copyFromFloats(1, 0, 0);
  88552. break;
  88553. case 1:
  88554. _this._add.copyFromFloats(-1, 0, 0);
  88555. break;
  88556. case 2:
  88557. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88558. break;
  88559. case 3:
  88560. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88561. break;
  88562. case 4:
  88563. _this._add.copyFromFloats(0, 0, 1);
  88564. break;
  88565. case 5:
  88566. _this._add.copyFromFloats(0, 0, -1);
  88567. break;
  88568. }
  88569. if (_this._attachedMesh) {
  88570. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88571. }
  88572. _this.position.addToRef(_this._add, _this._target);
  88573. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88574. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88575. scene._forcedViewPosition = _this.position;
  88576. });
  88577. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88578. scene._forcedViewPosition = null;
  88579. scene.updateTransformMatrix(true);
  88580. });
  88581. if (scene.activeCamera) {
  88582. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88583. }
  88584. }
  88585. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88586. get: function () {
  88587. return this._renderTargetTexture.samples;
  88588. },
  88589. set: function (value) {
  88590. this._renderTargetTexture.samples = value;
  88591. },
  88592. enumerable: true,
  88593. configurable: true
  88594. });
  88595. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88596. get: function () {
  88597. return this._renderTargetTexture.refreshRate;
  88598. },
  88599. set: function (value) {
  88600. this._renderTargetTexture.refreshRate = value;
  88601. },
  88602. enumerable: true,
  88603. configurable: true
  88604. });
  88605. ReflectionProbe.prototype.getScene = function () {
  88606. return this._scene;
  88607. };
  88608. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88609. get: function () {
  88610. return this._renderTargetTexture;
  88611. },
  88612. enumerable: true,
  88613. configurable: true
  88614. });
  88615. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88616. get: function () {
  88617. return this._renderTargetTexture.renderList;
  88618. },
  88619. enumerable: true,
  88620. configurable: true
  88621. });
  88622. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88623. this._attachedMesh = mesh;
  88624. };
  88625. /**
  88626. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88627. *
  88628. * @param renderingGroupId The rendering group id corresponding to its index
  88629. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88630. */
  88631. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88632. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88633. };
  88634. ReflectionProbe.prototype.dispose = function () {
  88635. var index = this._scene.reflectionProbes.indexOf(this);
  88636. if (index !== -1) {
  88637. // Remove from the scene if found
  88638. this._scene.reflectionProbes.splice(index, 1);
  88639. }
  88640. if (this._renderTargetTexture) {
  88641. this._renderTargetTexture.dispose();
  88642. this._renderTargetTexture = null;
  88643. }
  88644. };
  88645. return ReflectionProbe;
  88646. }());
  88647. BABYLON.ReflectionProbe = ReflectionProbe;
  88648. })(BABYLON || (BABYLON = {}));
  88649. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88650. "use strict";
  88651. var BABYLON;
  88652. (function (BABYLON) {
  88653. var Layer = /** @class */ (function () {
  88654. function Layer(name, imgUrl, scene, isBackground, color) {
  88655. this.name = name;
  88656. this.scale = new BABYLON.Vector2(1, 1);
  88657. this.offset = new BABYLON.Vector2(0, 0);
  88658. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88659. this.layerMask = 0x0FFFFFFF;
  88660. this._vertexBuffers = {};
  88661. // Events
  88662. /**
  88663. * An event triggered when the layer is disposed.
  88664. * @type {BABYLON.Observable}
  88665. */
  88666. this.onDisposeObservable = new BABYLON.Observable();
  88667. /**
  88668. * An event triggered before rendering the scene
  88669. * @type {BABYLON.Observable}
  88670. */
  88671. this.onBeforeRenderObservable = new BABYLON.Observable();
  88672. /**
  88673. * An event triggered after rendering the scene
  88674. * @type {BABYLON.Observable}
  88675. */
  88676. this.onAfterRenderObservable = new BABYLON.Observable();
  88677. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88678. this.isBackground = isBackground === undefined ? true : isBackground;
  88679. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88680. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88681. this._scene.layers.push(this);
  88682. var engine = this._scene.getEngine();
  88683. // VBO
  88684. var vertices = [];
  88685. vertices.push(1, 1);
  88686. vertices.push(-1, 1);
  88687. vertices.push(-1, -1);
  88688. vertices.push(1, -1);
  88689. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88690. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88691. this._createIndexBuffer();
  88692. // Effects
  88693. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  88694. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88695. }
  88696. Object.defineProperty(Layer.prototype, "onDispose", {
  88697. set: function (callback) {
  88698. if (this._onDisposeObserver) {
  88699. this.onDisposeObservable.remove(this._onDisposeObserver);
  88700. }
  88701. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88702. },
  88703. enumerable: true,
  88704. configurable: true
  88705. });
  88706. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88707. set: function (callback) {
  88708. if (this._onBeforeRenderObserver) {
  88709. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88710. }
  88711. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88712. },
  88713. enumerable: true,
  88714. configurable: true
  88715. });
  88716. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88717. set: function (callback) {
  88718. if (this._onAfterRenderObserver) {
  88719. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88720. }
  88721. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  88722. },
  88723. enumerable: true,
  88724. configurable: true
  88725. });
  88726. Layer.prototype._createIndexBuffer = function () {
  88727. var engine = this._scene.getEngine();
  88728. // Indices
  88729. var indices = [];
  88730. indices.push(0);
  88731. indices.push(1);
  88732. indices.push(2);
  88733. indices.push(0);
  88734. indices.push(2);
  88735. indices.push(3);
  88736. this._indexBuffer = engine.createIndexBuffer(indices);
  88737. };
  88738. Layer.prototype._rebuild = function () {
  88739. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88740. if (vb) {
  88741. vb._rebuild();
  88742. }
  88743. this._createIndexBuffer();
  88744. };
  88745. Layer.prototype.render = function () {
  88746. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  88747. // Check
  88748. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  88749. return;
  88750. var engine = this._scene.getEngine();
  88751. this.onBeforeRenderObservable.notifyObservers(this);
  88752. // Render
  88753. engine.enableEffect(currentEffect);
  88754. engine.setState(false);
  88755. // Texture
  88756. currentEffect.setTexture("textureSampler", this.texture);
  88757. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  88758. // Color
  88759. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  88760. // Scale / offset
  88761. currentEffect.setVector2("offset", this.offset);
  88762. currentEffect.setVector2("scale", this.scale);
  88763. // VBOs
  88764. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88765. // Draw order
  88766. if (!this.alphaTest) {
  88767. engine.setAlphaMode(this.alphaBlendingMode);
  88768. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88769. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88770. }
  88771. else {
  88772. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88773. }
  88774. this.onAfterRenderObservable.notifyObservers(this);
  88775. };
  88776. Layer.prototype.dispose = function () {
  88777. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88778. if (vertexBuffer) {
  88779. vertexBuffer.dispose();
  88780. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88781. }
  88782. if (this._indexBuffer) {
  88783. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88784. this._indexBuffer = null;
  88785. }
  88786. if (this.texture) {
  88787. this.texture.dispose();
  88788. this.texture = null;
  88789. }
  88790. // Remove from scene
  88791. var index = this._scene.layers.indexOf(this);
  88792. this._scene.layers.splice(index, 1);
  88793. // Callback
  88794. this.onDisposeObservable.notifyObservers(this);
  88795. this.onDisposeObservable.clear();
  88796. this.onAfterRenderObservable.clear();
  88797. this.onBeforeRenderObservable.clear();
  88798. };
  88799. return Layer;
  88800. }());
  88801. BABYLON.Layer = Layer;
  88802. })(BABYLON || (BABYLON = {}));
  88803. //# sourceMappingURL=babylon.layer.js.map
  88804. "use strict";
  88805. var BABYLON;
  88806. (function (BABYLON) {
  88807. var TextureTools = /** @class */ (function () {
  88808. function TextureTools() {
  88809. }
  88810. /**
  88811. * Uses the GPU to create a copy texture rescaled at a given size
  88812. * @param texture Texture to copy from
  88813. * @param width Desired width
  88814. * @param height Desired height
  88815. * @return Generated texture
  88816. */
  88817. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88818. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88819. var scene = texture.getScene();
  88820. var engine = scene.getEngine();
  88821. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88822. rtt.wrapU = texture.wrapU;
  88823. rtt.wrapV = texture.wrapV;
  88824. rtt.uOffset = texture.uOffset;
  88825. rtt.vOffset = texture.vOffset;
  88826. rtt.uScale = texture.uScale;
  88827. rtt.vScale = texture.vScale;
  88828. rtt.uAng = texture.uAng;
  88829. rtt.vAng = texture.vAng;
  88830. rtt.wAng = texture.wAng;
  88831. rtt.coordinatesIndex = texture.coordinatesIndex;
  88832. rtt.level = texture.level;
  88833. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88834. rtt._texture.isReady = false;
  88835. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88836. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88837. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88838. passPostProcess.getEffect().executeWhenCompiled(function () {
  88839. passPostProcess.onApply = function (effect) {
  88840. effect.setTexture("textureSampler", texture);
  88841. };
  88842. var internalTexture = rtt.getInternalTexture();
  88843. if (internalTexture) {
  88844. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88845. engine.unBindFramebuffer(internalTexture);
  88846. rtt.disposeFramebufferObjects();
  88847. passPostProcess.dispose();
  88848. internalTexture.isReady = true;
  88849. }
  88850. });
  88851. return rtt;
  88852. };
  88853. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88854. if (!scene._environmentBRDFTexture) {
  88855. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88856. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88857. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88858. scene._environmentBRDFTexture = texture;
  88859. }
  88860. return scene._environmentBRDFTexture;
  88861. };
  88862. 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=";
  88863. return TextureTools;
  88864. }());
  88865. BABYLON.TextureTools = TextureTools;
  88866. })(BABYLON || (BABYLON = {}));
  88867. //# sourceMappingURL=babylon.textureTools.js.map
  88868. "use strict";
  88869. var BABYLON;
  88870. (function (BABYLON) {
  88871. var FramingBehavior = /** @class */ (function () {
  88872. function FramingBehavior() {
  88873. this._mode = FramingBehavior.FitFrustumSidesMode;
  88874. this._radiusScale = 1.0;
  88875. this._positionScale = 0.5;
  88876. this._defaultElevation = 0.3;
  88877. this._elevationReturnTime = 1500;
  88878. this._elevationReturnWaitTime = 1000;
  88879. this._zoomStopsAnimation = false;
  88880. this._framingTime = 1500;
  88881. this._isPointerDown = false;
  88882. this._lastInteractionTime = -Infinity;
  88883. // Framing control
  88884. this._animatables = new Array();
  88885. this._betaIsAnimating = false;
  88886. }
  88887. Object.defineProperty(FramingBehavior.prototype, "name", {
  88888. get: function () {
  88889. return "Framing";
  88890. },
  88891. enumerable: true,
  88892. configurable: true
  88893. });
  88894. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88895. /**
  88896. * Gets current mode used by the behavior.
  88897. */
  88898. get: function () {
  88899. return this._mode;
  88900. },
  88901. /**
  88902. * Sets the current mode used by the behavior
  88903. */
  88904. set: function (mode) {
  88905. this._mode = mode;
  88906. },
  88907. enumerable: true,
  88908. configurable: true
  88909. });
  88910. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88911. /**
  88912. * Gets the scale applied to the radius
  88913. */
  88914. get: function () {
  88915. return this._radiusScale;
  88916. },
  88917. /**
  88918. * Sets the scale applied to the radius (1 by default)
  88919. */
  88920. set: function (radius) {
  88921. this._radiusScale = radius;
  88922. },
  88923. enumerable: true,
  88924. configurable: true
  88925. });
  88926. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88927. /**
  88928. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88929. */
  88930. get: function () {
  88931. return this._positionScale;
  88932. },
  88933. /**
  88934. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88935. */
  88936. set: function (scale) {
  88937. this._positionScale = scale;
  88938. },
  88939. enumerable: true,
  88940. configurable: true
  88941. });
  88942. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88943. /**
  88944. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88945. * behaviour is triggered, in radians.
  88946. */
  88947. get: function () {
  88948. return this._defaultElevation;
  88949. },
  88950. /**
  88951. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88952. * behaviour is triggered, in radians.
  88953. */
  88954. set: function (elevation) {
  88955. this._defaultElevation = elevation;
  88956. },
  88957. enumerable: true,
  88958. configurable: true
  88959. });
  88960. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88961. /**
  88962. * Gets the time (in milliseconds) taken to return to the default beta position.
  88963. * Negative value indicates camera should not return to default.
  88964. */
  88965. get: function () {
  88966. return this._elevationReturnTime;
  88967. },
  88968. /**
  88969. * Sets the time (in milliseconds) taken to return to the default beta position.
  88970. * Negative value indicates camera should not return to default.
  88971. */
  88972. set: function (speed) {
  88973. this._elevationReturnTime = speed;
  88974. },
  88975. enumerable: true,
  88976. configurable: true
  88977. });
  88978. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88979. /**
  88980. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88981. */
  88982. get: function () {
  88983. return this._elevationReturnWaitTime;
  88984. },
  88985. /**
  88986. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88987. */
  88988. set: function (time) {
  88989. this._elevationReturnWaitTime = time;
  88990. },
  88991. enumerable: true,
  88992. configurable: true
  88993. });
  88994. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88995. /**
  88996. * Gets the flag that indicates if user zooming should stop animation.
  88997. */
  88998. get: function () {
  88999. return this._zoomStopsAnimation;
  89000. },
  89001. /**
  89002. * Sets the flag that indicates if user zooming should stop animation.
  89003. */
  89004. set: function (flag) {
  89005. this._zoomStopsAnimation = flag;
  89006. },
  89007. enumerable: true,
  89008. configurable: true
  89009. });
  89010. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  89011. /**
  89012. * Gets the transition time when framing the mesh, in milliseconds
  89013. */
  89014. get: function () {
  89015. return this._framingTime;
  89016. },
  89017. /**
  89018. * Sets the transition time when framing the mesh, in milliseconds
  89019. */
  89020. set: function (time) {
  89021. this._framingTime = time;
  89022. },
  89023. enumerable: true,
  89024. configurable: true
  89025. });
  89026. FramingBehavior.prototype.init = function () {
  89027. // Do notihng
  89028. };
  89029. FramingBehavior.prototype.attach = function (camera) {
  89030. var _this = this;
  89031. this._attachedCamera = camera;
  89032. var scene = this._attachedCamera.getScene();
  89033. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89034. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89035. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89036. _this._isPointerDown = true;
  89037. return;
  89038. }
  89039. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89040. _this._isPointerDown = false;
  89041. }
  89042. });
  89043. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89044. if (mesh) {
  89045. _this.zoomOnMesh(mesh);
  89046. }
  89047. });
  89048. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89049. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89050. _this._applyUserInteraction();
  89051. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89052. // back to the default position after a given timeout
  89053. _this._maintainCameraAboveGround();
  89054. });
  89055. };
  89056. FramingBehavior.prototype.detach = function () {
  89057. if (!this._attachedCamera) {
  89058. return;
  89059. }
  89060. var scene = this._attachedCamera.getScene();
  89061. if (this._onPrePointerObservableObserver) {
  89062. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89063. }
  89064. if (this._onAfterCheckInputsObserver) {
  89065. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89066. }
  89067. if (this._onMeshTargetChangedObserver) {
  89068. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89069. }
  89070. this._attachedCamera = null;
  89071. };
  89072. /**
  89073. * Targets the given mesh and updates zoom level accordingly.
  89074. * @param mesh The mesh to target.
  89075. * @param radius Optional. If a cached radius position already exists, overrides default.
  89076. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89077. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89078. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89079. */
  89080. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89081. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89082. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89083. mesh.computeWorldMatrix(true);
  89084. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89085. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89086. };
  89087. /**
  89088. * Targets the given mesh with its children and updates zoom level accordingly.
  89089. * @param mesh The mesh to target.
  89090. * @param radius Optional. If a cached radius position already exists, overrides default.
  89091. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89092. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89093. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89094. */
  89095. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89096. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89097. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89098. mesh.computeWorldMatrix(true);
  89099. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89100. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89101. };
  89102. /**
  89103. * Targets the given meshes with their children and updates zoom level accordingly.
  89104. * @param meshes The mesh to target.
  89105. * @param radius Optional. If a cached radius position already exists, overrides default.
  89106. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89107. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89108. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89109. */
  89110. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89111. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89112. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89113. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89114. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89115. for (var i = 0; i < meshes.length; i++) {
  89116. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89117. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89118. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89119. }
  89120. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89121. };
  89122. /**
  89123. * Targets the given mesh and updates zoom level accordingly.
  89124. * @param mesh The mesh to target.
  89125. * @param radius Optional. If a cached radius position already exists, overrides default.
  89126. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89127. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89128. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89129. */
  89130. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89131. var _this = this;
  89132. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89133. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89134. var zoomTarget;
  89135. if (!this._attachedCamera) {
  89136. return;
  89137. }
  89138. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89139. var bottom = minimumWorld.y;
  89140. var top = maximumWorld.y;
  89141. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89142. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89143. if (focusOnOriginXZ) {
  89144. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89145. }
  89146. else {
  89147. var centerWorld = minimumWorld.add(radiusWorld);
  89148. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89149. }
  89150. if (!this._vectorTransition) {
  89151. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89152. }
  89153. this._betaIsAnimating = true;
  89154. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89155. if (animatable) {
  89156. this._animatables.push(animatable);
  89157. }
  89158. // sets the radius and lower radius bounds
  89159. // Small delta ensures camera is not always at lower zoom limit.
  89160. var radius = 0;
  89161. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89162. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89163. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89164. radius = position;
  89165. }
  89166. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89167. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89168. if (this._attachedCamera.lowerRadiusLimit === null) {
  89169. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89170. }
  89171. }
  89172. // Set sensibilities
  89173. var extend = maximumWorld.subtract(minimumWorld).length();
  89174. this._attachedCamera.panningSensibility = 5000 / extend;
  89175. this._attachedCamera.wheelPrecision = 100 / radius;
  89176. // transition to new radius
  89177. if (!this._radiusTransition) {
  89178. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89179. }
  89180. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89181. _this.stopAllAnimations();
  89182. if (onAnimationEnd) {
  89183. onAnimationEnd();
  89184. }
  89185. if (_this._attachedCamera) {
  89186. _this._attachedCamera.storeState();
  89187. }
  89188. });
  89189. if (animatable) {
  89190. this._animatables.push(animatable);
  89191. }
  89192. };
  89193. /**
  89194. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89195. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89196. * frustum width.
  89197. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89198. * to fully enclose the mesh in the viewing frustum.
  89199. */
  89200. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89201. var size = maximumWorld.subtract(minimumWorld);
  89202. var boxVectorGlobalDiagonal = size.length();
  89203. var frustumSlope = this._getFrustumSlope();
  89204. // Formula for setting distance
  89205. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89206. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89207. // Horizon distance
  89208. var radius = radiusWithoutFraming * this._radiusScale;
  89209. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89210. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89211. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89212. var camera = this._attachedCamera;
  89213. if (!camera) {
  89214. return 0;
  89215. }
  89216. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89217. // Don't exceed the requested limit
  89218. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89219. }
  89220. // Don't exceed the upper radius limit
  89221. if (camera.upperRadiusLimit) {
  89222. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89223. }
  89224. return distance;
  89225. };
  89226. /**
  89227. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89228. * is automatically returned to its default position (expected to be above ground plane).
  89229. */
  89230. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89231. var _this = this;
  89232. if (this._elevationReturnTime < 0) {
  89233. return;
  89234. }
  89235. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89236. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89237. var limitBeta = Math.PI * 0.5;
  89238. // Bring the camera back up if below the ground plane
  89239. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89240. this._betaIsAnimating = true;
  89241. //Transition to new position
  89242. this.stopAllAnimations();
  89243. if (!this._betaTransition) {
  89244. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89245. }
  89246. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89247. _this._clearAnimationLocks();
  89248. _this.stopAllAnimations();
  89249. });
  89250. if (animatabe) {
  89251. this._animatables.push(animatabe);
  89252. }
  89253. }
  89254. };
  89255. /**
  89256. * Returns the frustum slope based on the canvas ratio and camera FOV
  89257. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89258. */
  89259. FramingBehavior.prototype._getFrustumSlope = function () {
  89260. // Calculate the viewport ratio
  89261. // Aspect Ratio is Height/Width.
  89262. var camera = this._attachedCamera;
  89263. if (!camera) {
  89264. return BABYLON.Vector2.Zero();
  89265. }
  89266. var engine = camera.getScene().getEngine();
  89267. var aspectRatio = engine.getAspectRatio(camera);
  89268. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89269. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89270. var frustumSlopeY = Math.tan(camera.fov / 2);
  89271. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89272. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89273. // along the forward vector.
  89274. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89275. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89276. };
  89277. /**
  89278. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89279. */
  89280. FramingBehavior.prototype._clearAnimationLocks = function () {
  89281. this._betaIsAnimating = false;
  89282. };
  89283. /**
  89284. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89285. */
  89286. FramingBehavior.prototype._applyUserInteraction = function () {
  89287. if (this.isUserIsMoving) {
  89288. this._lastInteractionTime = BABYLON.Tools.Now;
  89289. this.stopAllAnimations();
  89290. this._clearAnimationLocks();
  89291. }
  89292. };
  89293. /**
  89294. * Stops and removes all animations that have been applied to the camera
  89295. */
  89296. FramingBehavior.prototype.stopAllAnimations = function () {
  89297. if (this._attachedCamera) {
  89298. this._attachedCamera.animations = [];
  89299. }
  89300. while (this._animatables.length) {
  89301. if (this._animatables[0]) {
  89302. this._animatables[0].onAnimationEnd = null;
  89303. this._animatables[0].stop();
  89304. }
  89305. this._animatables.shift();
  89306. }
  89307. };
  89308. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89309. /**
  89310. * Gets a value indicating if the user is moving the camera
  89311. */
  89312. get: function () {
  89313. if (!this._attachedCamera) {
  89314. return false;
  89315. }
  89316. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89317. this._attachedCamera.inertialBetaOffset !== 0 ||
  89318. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89319. this._attachedCamera.inertialPanningX !== 0 ||
  89320. this._attachedCamera.inertialPanningY !== 0 ||
  89321. this._isPointerDown;
  89322. },
  89323. enumerable: true,
  89324. configurable: true
  89325. });
  89326. /**
  89327. * The easing function used by animations
  89328. */
  89329. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89330. /**
  89331. * The easing mode used by animations
  89332. */
  89333. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89334. // Statics
  89335. /**
  89336. * The camera can move all the way towards the mesh.
  89337. */
  89338. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89339. /**
  89340. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89341. */
  89342. FramingBehavior.FitFrustumSidesMode = 1;
  89343. return FramingBehavior;
  89344. }());
  89345. BABYLON.FramingBehavior = FramingBehavior;
  89346. })(BABYLON || (BABYLON = {}));
  89347. //# sourceMappingURL=babylon.framingBehavior.js.map
  89348. "use strict";
  89349. var BABYLON;
  89350. (function (BABYLON) {
  89351. /**
  89352. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89353. */
  89354. var BouncingBehavior = /** @class */ (function () {
  89355. function BouncingBehavior() {
  89356. /**
  89357. * The duration of the animation, in milliseconds
  89358. */
  89359. this.transitionDuration = 450;
  89360. /**
  89361. * Length of the distance animated by the transition when lower radius is reached
  89362. */
  89363. this.lowerRadiusTransitionRange = 2;
  89364. /**
  89365. * Length of the distance animated by the transition when upper radius is reached
  89366. */
  89367. this.upperRadiusTransitionRange = -2;
  89368. this._autoTransitionRange = false;
  89369. // Animations
  89370. this._radiusIsAnimating = false;
  89371. this._radiusBounceTransition = null;
  89372. this._animatables = new Array();
  89373. }
  89374. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89375. get: function () {
  89376. return "Bouncing";
  89377. },
  89378. enumerable: true,
  89379. configurable: true
  89380. });
  89381. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89382. /**
  89383. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89384. */
  89385. get: function () {
  89386. return this._autoTransitionRange;
  89387. },
  89388. /**
  89389. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89390. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89391. */
  89392. set: function (value) {
  89393. var _this = this;
  89394. if (this._autoTransitionRange === value) {
  89395. return;
  89396. }
  89397. this._autoTransitionRange = value;
  89398. var camera = this._attachedCamera;
  89399. if (!camera) {
  89400. return;
  89401. }
  89402. if (value) {
  89403. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89404. if (!mesh) {
  89405. return;
  89406. }
  89407. mesh.computeWorldMatrix(true);
  89408. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89409. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89410. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89411. });
  89412. }
  89413. else if (this._onMeshTargetChangedObserver) {
  89414. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89415. }
  89416. },
  89417. enumerable: true,
  89418. configurable: true
  89419. });
  89420. BouncingBehavior.prototype.init = function () {
  89421. // Do notihng
  89422. };
  89423. BouncingBehavior.prototype.attach = function (camera) {
  89424. var _this = this;
  89425. this._attachedCamera = camera;
  89426. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89427. if (!_this._attachedCamera) {
  89428. return;
  89429. }
  89430. // Add the bounce animation to the lower radius limit
  89431. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89432. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89433. }
  89434. // Add the bounce animation to the upper radius limit
  89435. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89436. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89437. }
  89438. });
  89439. };
  89440. BouncingBehavior.prototype.detach = function () {
  89441. if (!this._attachedCamera) {
  89442. return;
  89443. }
  89444. if (this._onAfterCheckInputsObserver) {
  89445. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89446. }
  89447. if (this._onMeshTargetChangedObserver) {
  89448. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89449. }
  89450. this._attachedCamera = null;
  89451. };
  89452. /**
  89453. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89454. * @param radiusLimit The limit to check against.
  89455. * @return Bool to indicate if at limit.
  89456. */
  89457. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89458. if (!this._attachedCamera) {
  89459. return false;
  89460. }
  89461. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89462. return true;
  89463. }
  89464. return false;
  89465. };
  89466. /**
  89467. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89468. * @param radiusDelta The delta by which to animate to. Can be negative.
  89469. */
  89470. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89471. var _this = this;
  89472. if (!this._attachedCamera) {
  89473. return;
  89474. }
  89475. if (!this._radiusBounceTransition) {
  89476. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89477. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89478. }
  89479. // Prevent zoom until bounce has completed
  89480. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89481. this._attachedCamera.wheelPrecision = Infinity;
  89482. this._attachedCamera.inertialRadiusOffset = 0;
  89483. // Animate to the radius limit
  89484. this.stopAllAnimations();
  89485. this._radiusIsAnimating = true;
  89486. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89487. if (animatable) {
  89488. this._animatables.push(animatable);
  89489. }
  89490. };
  89491. /**
  89492. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89493. */
  89494. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89495. this._radiusIsAnimating = false;
  89496. if (this._attachedCamera) {
  89497. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89498. }
  89499. };
  89500. /**
  89501. * Stops and removes all animations that have been applied to the camera
  89502. */
  89503. BouncingBehavior.prototype.stopAllAnimations = function () {
  89504. if (this._attachedCamera) {
  89505. this._attachedCamera.animations = [];
  89506. }
  89507. while (this._animatables.length) {
  89508. this._animatables[0].onAnimationEnd = null;
  89509. this._animatables[0].stop();
  89510. this._animatables.shift();
  89511. }
  89512. };
  89513. /**
  89514. * The easing function used by animations
  89515. */
  89516. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89517. /**
  89518. * The easing mode used by animations
  89519. */
  89520. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89521. return BouncingBehavior;
  89522. }());
  89523. BABYLON.BouncingBehavior = BouncingBehavior;
  89524. })(BABYLON || (BABYLON = {}));
  89525. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89526. "use strict";
  89527. var BABYLON;
  89528. (function (BABYLON) {
  89529. var AutoRotationBehavior = /** @class */ (function () {
  89530. function AutoRotationBehavior() {
  89531. this._zoomStopsAnimation = false;
  89532. this._idleRotationSpeed = 0.05;
  89533. this._idleRotationWaitTime = 2000;
  89534. this._idleRotationSpinupTime = 2000;
  89535. this._isPointerDown = false;
  89536. this._lastFrameTime = null;
  89537. this._lastInteractionTime = -Infinity;
  89538. this._cameraRotationSpeed = 0;
  89539. this._lastFrameRadius = 0;
  89540. }
  89541. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89542. get: function () {
  89543. return "AutoRotation";
  89544. },
  89545. enumerable: true,
  89546. configurable: true
  89547. });
  89548. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89549. /**
  89550. * Gets the flag that indicates if user zooming should stop animation.
  89551. */
  89552. get: function () {
  89553. return this._zoomStopsAnimation;
  89554. },
  89555. /**
  89556. * Sets the flag that indicates if user zooming should stop animation.
  89557. */
  89558. set: function (flag) {
  89559. this._zoomStopsAnimation = flag;
  89560. },
  89561. enumerable: true,
  89562. configurable: true
  89563. });
  89564. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89565. /**
  89566. * Gets the default speed at which the camera rotates around the model.
  89567. */
  89568. get: function () {
  89569. return this._idleRotationSpeed;
  89570. },
  89571. /**
  89572. * Sets the default speed at which the camera rotates around the model.
  89573. */
  89574. set: function (speed) {
  89575. this._idleRotationSpeed = speed;
  89576. },
  89577. enumerable: true,
  89578. configurable: true
  89579. });
  89580. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89581. /**
  89582. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89583. */
  89584. get: function () {
  89585. return this._idleRotationWaitTime;
  89586. },
  89587. /**
  89588. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89589. */
  89590. set: function (time) {
  89591. this._idleRotationWaitTime = time;
  89592. },
  89593. enumerable: true,
  89594. configurable: true
  89595. });
  89596. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89597. /**
  89598. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89599. */
  89600. get: function () {
  89601. return this._idleRotationSpinupTime;
  89602. },
  89603. /**
  89604. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89605. */
  89606. set: function (time) {
  89607. this._idleRotationSpinupTime = time;
  89608. },
  89609. enumerable: true,
  89610. configurable: true
  89611. });
  89612. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89613. /**
  89614. * Gets a value indicating if the camera is currently rotating because of this behavior
  89615. */
  89616. get: function () {
  89617. return Math.abs(this._cameraRotationSpeed) > 0;
  89618. },
  89619. enumerable: true,
  89620. configurable: true
  89621. });
  89622. AutoRotationBehavior.prototype.init = function () {
  89623. // Do notihng
  89624. };
  89625. AutoRotationBehavior.prototype.attach = function (camera) {
  89626. var _this = this;
  89627. this._attachedCamera = camera;
  89628. var scene = this._attachedCamera.getScene();
  89629. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89630. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89631. _this._isPointerDown = true;
  89632. return;
  89633. }
  89634. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89635. _this._isPointerDown = false;
  89636. }
  89637. });
  89638. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89639. var now = BABYLON.Tools.Now;
  89640. var dt = 0;
  89641. if (_this._lastFrameTime != null) {
  89642. dt = now - _this._lastFrameTime;
  89643. }
  89644. _this._lastFrameTime = now;
  89645. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89646. _this._applyUserInteraction();
  89647. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89648. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89649. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89650. // Step camera rotation by rotation speed
  89651. if (_this._attachedCamera) {
  89652. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89653. }
  89654. });
  89655. };
  89656. AutoRotationBehavior.prototype.detach = function () {
  89657. if (!this._attachedCamera) {
  89658. return;
  89659. }
  89660. var scene = this._attachedCamera.getScene();
  89661. if (this._onPrePointerObservableObserver) {
  89662. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89663. }
  89664. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89665. this._attachedCamera = null;
  89666. };
  89667. /**
  89668. * Returns true if user is scrolling.
  89669. * @return true if user is scrolling.
  89670. */
  89671. AutoRotationBehavior.prototype._userIsZooming = function () {
  89672. if (!this._attachedCamera) {
  89673. return false;
  89674. }
  89675. return this._attachedCamera.inertialRadiusOffset !== 0;
  89676. };
  89677. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89678. if (!this._attachedCamera) {
  89679. return false;
  89680. }
  89681. var zoomHasHitLimit = false;
  89682. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89683. zoomHasHitLimit = true;
  89684. }
  89685. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89686. this._lastFrameRadius = this._attachedCamera.radius;
  89687. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  89688. };
  89689. /**
  89690. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89691. */
  89692. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  89693. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  89694. this._lastInteractionTime = BABYLON.Tools.Now;
  89695. }
  89696. };
  89697. // Tools
  89698. AutoRotationBehavior.prototype._userIsMoving = function () {
  89699. if (!this._attachedCamera) {
  89700. return false;
  89701. }
  89702. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89703. this._attachedCamera.inertialBetaOffset !== 0 ||
  89704. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89705. this._attachedCamera.inertialPanningX !== 0 ||
  89706. this._attachedCamera.inertialPanningY !== 0 ||
  89707. this._isPointerDown;
  89708. };
  89709. return AutoRotationBehavior;
  89710. }());
  89711. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89712. })(BABYLON || (BABYLON = {}));
  89713. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89714. "use strict";
  89715. var BABYLON;
  89716. (function (BABYLON) {
  89717. var NullEngineOptions = /** @class */ (function () {
  89718. function NullEngineOptions() {
  89719. this.renderWidth = 512;
  89720. this.renderHeight = 256;
  89721. this.textureSize = 512;
  89722. this.deterministicLockstep = false;
  89723. this.lockstepMaxSteps = 4;
  89724. }
  89725. return NullEngineOptions;
  89726. }());
  89727. BABYLON.NullEngineOptions = NullEngineOptions;
  89728. /**
  89729. * The null engine class provides support for headless version of babylon.js.
  89730. * This can be used in server side scenario or for testing purposes
  89731. */
  89732. var NullEngine = /** @class */ (function (_super) {
  89733. __extends(NullEngine, _super);
  89734. function NullEngine(options) {
  89735. if (options === void 0) { options = new NullEngineOptions(); }
  89736. var _this = _super.call(this, null) || this;
  89737. if (options.deterministicLockstep === undefined) {
  89738. options.deterministicLockstep = false;
  89739. }
  89740. if (options.lockstepMaxSteps === undefined) {
  89741. options.lockstepMaxSteps = 4;
  89742. }
  89743. _this._options = options;
  89744. // Init caps
  89745. // We consider we are on a webgl1 capable device
  89746. _this._caps = new BABYLON.EngineCapabilities();
  89747. _this._caps.maxTexturesImageUnits = 16;
  89748. _this._caps.maxVertexTextureImageUnits = 16;
  89749. _this._caps.maxTextureSize = 512;
  89750. _this._caps.maxCubemapTextureSize = 512;
  89751. _this._caps.maxRenderTextureSize = 512;
  89752. _this._caps.maxVertexAttribs = 16;
  89753. _this._caps.maxVaryingVectors = 16;
  89754. _this._caps.maxFragmentUniformVectors = 16;
  89755. _this._caps.maxVertexUniformVectors = 16;
  89756. // Extensions
  89757. _this._caps.standardDerivatives = false;
  89758. _this._caps.astc = null;
  89759. _this._caps.s3tc = null;
  89760. _this._caps.pvrtc = null;
  89761. _this._caps.etc1 = null;
  89762. _this._caps.etc2 = null;
  89763. _this._caps.textureAnisotropicFilterExtension = null;
  89764. _this._caps.maxAnisotropy = 0;
  89765. _this._caps.uintIndices = false;
  89766. _this._caps.fragmentDepthSupported = false;
  89767. _this._caps.highPrecisionShaderSupported = true;
  89768. _this._caps.colorBufferFloat = false;
  89769. _this._caps.textureFloat = false;
  89770. _this._caps.textureFloatLinearFiltering = false;
  89771. _this._caps.textureFloatRender = false;
  89772. _this._caps.textureHalfFloat = false;
  89773. _this._caps.textureHalfFloatLinearFiltering = false;
  89774. _this._caps.textureHalfFloatRender = false;
  89775. _this._caps.textureLOD = false;
  89776. _this._caps.drawBuffersExtension = false;
  89777. _this._caps.depthTextureExtension = false;
  89778. _this._caps.vertexArrayObject = false;
  89779. _this._caps.instancedArrays = false;
  89780. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  89781. // Wrappers
  89782. if (typeof URL === "undefined") {
  89783. URL = {
  89784. createObjectURL: function () { },
  89785. revokeObjectURL: function () { }
  89786. };
  89787. }
  89788. if (typeof Blob === "undefined") {
  89789. Blob = function () { };
  89790. }
  89791. return _this;
  89792. }
  89793. NullEngine.prototype.isDeterministicLockStep = function () {
  89794. return this._options.deterministicLockstep;
  89795. };
  89796. NullEngine.prototype.getLockstepMaxSteps = function () {
  89797. return this._options.lockstepMaxSteps;
  89798. };
  89799. NullEngine.prototype.getHardwareScalingLevel = function () {
  89800. return 1.0;
  89801. };
  89802. NullEngine.prototype.createVertexBuffer = function (vertices) {
  89803. return {
  89804. capacity: 0,
  89805. references: 1,
  89806. is32Bits: false
  89807. };
  89808. };
  89809. NullEngine.prototype.createIndexBuffer = function (indices) {
  89810. return {
  89811. capacity: 0,
  89812. references: 1,
  89813. is32Bits: false
  89814. };
  89815. };
  89816. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  89817. if (stencil === void 0) { stencil = false; }
  89818. };
  89819. NullEngine.prototype.getRenderWidth = function (useScreen) {
  89820. if (useScreen === void 0) { useScreen = false; }
  89821. if (!useScreen && this._currentRenderTarget) {
  89822. return this._currentRenderTarget.width;
  89823. }
  89824. return this._options.renderWidth;
  89825. };
  89826. NullEngine.prototype.getRenderHeight = function (useScreen) {
  89827. if (useScreen === void 0) { useScreen = false; }
  89828. if (!useScreen && this._currentRenderTarget) {
  89829. return this._currentRenderTarget.height;
  89830. }
  89831. return this._options.renderHeight;
  89832. };
  89833. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  89834. this._cachedViewport = viewport;
  89835. };
  89836. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  89837. return {
  89838. transformFeedback: null,
  89839. __SPECTOR_rebuildProgram: null
  89840. };
  89841. };
  89842. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  89843. return [];
  89844. };
  89845. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  89846. return [];
  89847. };
  89848. NullEngine.prototype.bindSamplers = function (effect) {
  89849. this._currentEffect = null;
  89850. };
  89851. NullEngine.prototype.enableEffect = function (effect) {
  89852. this._currentEffect = effect;
  89853. if (effect.onBind) {
  89854. effect.onBind(effect);
  89855. }
  89856. effect.onBindObservable.notifyObservers(effect);
  89857. };
  89858. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  89859. if (zOffset === void 0) { zOffset = 0; }
  89860. if (reverseSide === void 0) { reverseSide = false; }
  89861. };
  89862. NullEngine.prototype.setIntArray = function (uniform, array) {
  89863. };
  89864. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  89865. };
  89866. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  89867. };
  89868. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  89869. };
  89870. NullEngine.prototype.setFloatArray = function (uniform, array) {
  89871. };
  89872. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  89873. };
  89874. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  89875. };
  89876. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  89877. };
  89878. NullEngine.prototype.setArray = function (uniform, array) {
  89879. };
  89880. NullEngine.prototype.setArray2 = function (uniform, array) {
  89881. };
  89882. NullEngine.prototype.setArray3 = function (uniform, array) {
  89883. };
  89884. NullEngine.prototype.setArray4 = function (uniform, array) {
  89885. };
  89886. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  89887. };
  89888. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  89889. };
  89890. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  89891. };
  89892. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  89893. };
  89894. NullEngine.prototype.setFloat = function (uniform, value) {
  89895. };
  89896. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  89897. };
  89898. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  89899. };
  89900. NullEngine.prototype.setBool = function (uniform, bool) {
  89901. };
  89902. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  89903. };
  89904. NullEngine.prototype.setColor3 = function (uniform, color3) {
  89905. };
  89906. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  89907. };
  89908. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  89909. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  89910. if (this._alphaMode === mode) {
  89911. return;
  89912. }
  89913. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  89914. if (!noDepthWriteChange) {
  89915. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  89916. }
  89917. this._alphaMode = mode;
  89918. };
  89919. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  89920. };
  89921. NullEngine.prototype.wipeCaches = function (bruteForce) {
  89922. if (this.preventCacheWipeBetweenFrames) {
  89923. return;
  89924. }
  89925. this.resetTextureCache();
  89926. this._currentEffect = null;
  89927. if (bruteForce) {
  89928. this._currentProgram = null;
  89929. this._stencilState.reset();
  89930. this._depthCullingState.reset();
  89931. this._alphaState.reset();
  89932. }
  89933. this._cachedVertexBuffers = null;
  89934. this._cachedIndexBuffer = null;
  89935. this._cachedEffectForVertexBuffers = null;
  89936. };
  89937. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  89938. };
  89939. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  89940. };
  89941. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  89942. };
  89943. NullEngine.prototype._createTexture = function () {
  89944. return {};
  89945. };
  89946. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  89947. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  89948. if (onLoad === void 0) { onLoad = null; }
  89949. if (onError === void 0) { onError = null; }
  89950. if (buffer === void 0) { buffer = null; }
  89951. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  89952. var url = String(urlArg);
  89953. texture.url = url;
  89954. texture.generateMipMaps = !noMipmap;
  89955. texture.samplingMode = samplingMode;
  89956. texture.invertY = invertY;
  89957. texture.baseWidth = this._options.textureSize;
  89958. texture.baseHeight = this._options.textureSize;
  89959. texture.width = this._options.textureSize;
  89960. texture.height = this._options.textureSize;
  89961. if (format) {
  89962. texture.format = format;
  89963. }
  89964. texture.isReady = true;
  89965. if (onLoad) {
  89966. onLoad();
  89967. }
  89968. return texture;
  89969. };
  89970. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  89971. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  89972. if (options !== undefined && typeof options === "object") {
  89973. fullOptions.generateMipMaps = options.generateMipMaps;
  89974. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  89975. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  89976. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  89977. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  89978. }
  89979. else {
  89980. fullOptions.generateMipMaps = options;
  89981. fullOptions.generateDepthBuffer = true;
  89982. fullOptions.generateStencilBuffer = false;
  89983. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89984. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  89985. }
  89986. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  89987. var width = size.width || size;
  89988. var height = size.height || size;
  89989. texture._depthStencilBuffer = {};
  89990. texture._framebuffer = {};
  89991. texture.baseWidth = width;
  89992. texture.baseHeight = height;
  89993. texture.width = width;
  89994. texture.height = height;
  89995. texture.isReady = true;
  89996. texture.samples = 1;
  89997. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  89998. texture.samplingMode = fullOptions.samplingMode;
  89999. texture.type = fullOptions.type;
  90000. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  90001. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  90002. return texture;
  90003. };
  90004. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  90005. texture.samplingMode = samplingMode;
  90006. };
  90007. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  90008. if (this._currentRenderTarget) {
  90009. this.unBindFramebuffer(this._currentRenderTarget);
  90010. }
  90011. this._currentRenderTarget = texture;
  90012. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  90013. if (this._cachedViewport && !forceFullscreenViewport) {
  90014. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  90015. }
  90016. };
  90017. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  90018. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  90019. this._currentRenderTarget = null;
  90020. if (onBeforeUnbind) {
  90021. if (texture._MSAAFramebuffer) {
  90022. this._currentFramebuffer = texture._framebuffer;
  90023. }
  90024. onBeforeUnbind();
  90025. }
  90026. this._currentFramebuffer = null;
  90027. };
  90028. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  90029. var vbo = {
  90030. capacity: 1,
  90031. references: 1,
  90032. is32Bits: false
  90033. };
  90034. return vbo;
  90035. };
  90036. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90037. if (offset === void 0) { offset = 0; }
  90038. };
  90039. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  90040. };
  90041. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90042. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90043. this._boundTexturesCache[this._activeChannel] = texture;
  90044. }
  90045. };
  90046. NullEngine.prototype._bindTexture = function (channel, texture) {
  90047. if (channel < 0) {
  90048. return;
  90049. }
  90050. this._bindTextureDirectly(0, texture);
  90051. };
  90052. NullEngine.prototype._releaseBuffer = function (buffer) {
  90053. buffer.references--;
  90054. if (buffer.references === 0) {
  90055. return true;
  90056. }
  90057. return false;
  90058. };
  90059. return NullEngine;
  90060. }(BABYLON.Engine));
  90061. BABYLON.NullEngine = NullEngine;
  90062. })(BABYLON || (BABYLON = {}));
  90063. //# sourceMappingURL=babylon.nullEngine.js.map
  90064. "use strict";
  90065. var BABYLON;
  90066. (function (BABYLON) {
  90067. /**
  90068. * This class can be used to get instrumentation data from a Babylon engine
  90069. */
  90070. var EngineInstrumentation = /** @class */ (function () {
  90071. function EngineInstrumentation(engine) {
  90072. this.engine = engine;
  90073. this._captureGPUFrameTime = false;
  90074. this._gpuFrameTime = new BABYLON.PerfCounter();
  90075. this._captureShaderCompilationTime = false;
  90076. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90077. // Observers
  90078. this._onBeginFrameObserver = null;
  90079. this._onEndFrameObserver = null;
  90080. this._onBeforeShaderCompilationObserver = null;
  90081. this._onAfterShaderCompilationObserver = null;
  90082. }
  90083. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90084. // Properties
  90085. /**
  90086. * Gets the perf counter used for GPU frame time
  90087. */
  90088. get: function () {
  90089. return this._gpuFrameTime;
  90090. },
  90091. enumerable: true,
  90092. configurable: true
  90093. });
  90094. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90095. /**
  90096. * Gets the GPU frame time capture status
  90097. */
  90098. get: function () {
  90099. return this._captureGPUFrameTime;
  90100. },
  90101. /**
  90102. * Enable or disable the GPU frame time capture
  90103. */
  90104. set: function (value) {
  90105. var _this = this;
  90106. if (value === this._captureGPUFrameTime) {
  90107. return;
  90108. }
  90109. this._captureGPUFrameTime = value;
  90110. if (value) {
  90111. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90112. if (!_this._gpuFrameTimeToken) {
  90113. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90114. }
  90115. });
  90116. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90117. if (!_this._gpuFrameTimeToken) {
  90118. return;
  90119. }
  90120. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90121. if (time > -1) {
  90122. _this._gpuFrameTimeToken = null;
  90123. _this._gpuFrameTime.fetchNewFrame();
  90124. _this._gpuFrameTime.addCount(time, true);
  90125. }
  90126. });
  90127. }
  90128. else {
  90129. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90130. this._onBeginFrameObserver = null;
  90131. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90132. this._onEndFrameObserver = null;
  90133. }
  90134. },
  90135. enumerable: true,
  90136. configurable: true
  90137. });
  90138. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90139. /**
  90140. * Gets the perf counter used for shader compilation time
  90141. */
  90142. get: function () {
  90143. return this._shaderCompilationTime;
  90144. },
  90145. enumerable: true,
  90146. configurable: true
  90147. });
  90148. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90149. /**
  90150. * Gets the shader compilation time capture status
  90151. */
  90152. get: function () {
  90153. return this._captureShaderCompilationTime;
  90154. },
  90155. /**
  90156. * Enable or disable the shader compilation time capture
  90157. */
  90158. set: function (value) {
  90159. var _this = this;
  90160. if (value === this._captureShaderCompilationTime) {
  90161. return;
  90162. }
  90163. this._captureShaderCompilationTime = value;
  90164. if (value) {
  90165. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90166. _this._shaderCompilationTime.fetchNewFrame();
  90167. _this._shaderCompilationTime.beginMonitoring();
  90168. });
  90169. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90170. _this._shaderCompilationTime.endMonitoring();
  90171. });
  90172. }
  90173. else {
  90174. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90175. this._onBeforeShaderCompilationObserver = null;
  90176. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90177. this._onAfterShaderCompilationObserver = null;
  90178. }
  90179. },
  90180. enumerable: true,
  90181. configurable: true
  90182. });
  90183. EngineInstrumentation.prototype.dispose = function () {
  90184. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90185. this._onBeginFrameObserver = null;
  90186. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90187. this._onEndFrameObserver = null;
  90188. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90189. this._onBeforeShaderCompilationObserver = null;
  90190. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90191. this._onAfterShaderCompilationObserver = null;
  90192. this.engine = null;
  90193. };
  90194. return EngineInstrumentation;
  90195. }());
  90196. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90197. })(BABYLON || (BABYLON = {}));
  90198. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90199. "use strict";
  90200. var BABYLON;
  90201. (function (BABYLON) {
  90202. /**
  90203. * This class can be used to get instrumentation data from a Babylon engine
  90204. */
  90205. var SceneInstrumentation = /** @class */ (function () {
  90206. function SceneInstrumentation(scene) {
  90207. var _this = this;
  90208. this.scene = scene;
  90209. this._captureActiveMeshesEvaluationTime = false;
  90210. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90211. this._captureRenderTargetsRenderTime = false;
  90212. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90213. this._captureFrameTime = false;
  90214. this._frameTime = new BABYLON.PerfCounter();
  90215. this._captureRenderTime = false;
  90216. this._renderTime = new BABYLON.PerfCounter();
  90217. this._captureInterFrameTime = false;
  90218. this._interFrameTime = new BABYLON.PerfCounter();
  90219. this._captureParticlesRenderTime = false;
  90220. this._particlesRenderTime = new BABYLON.PerfCounter();
  90221. this._captureSpritesRenderTime = false;
  90222. this._spritesRenderTime = new BABYLON.PerfCounter();
  90223. this._capturePhysicsTime = false;
  90224. this._physicsTime = new BABYLON.PerfCounter();
  90225. this._captureAnimationsTime = false;
  90226. this._animationsTime = new BABYLON.PerfCounter();
  90227. // Observers
  90228. this._onBeforeActiveMeshesEvaluationObserver = null;
  90229. this._onAfterActiveMeshesEvaluationObserver = null;
  90230. this._onBeforeRenderTargetsRenderObserver = null;
  90231. this._onAfterRenderTargetsRenderObserver = null;
  90232. this._onAfterRenderObserver = null;
  90233. this._onBeforeDrawPhaseObserver = null;
  90234. this._onAfterDrawPhaseObserver = null;
  90235. this._onBeforeAnimationsObserver = null;
  90236. this._onBeforeParticlesRenderingObserver = null;
  90237. this._onAfterParticlesRenderingObserver = null;
  90238. this._onBeforeSpritesRenderingObserver = null;
  90239. this._onAfterSpritesRenderingObserver = null;
  90240. this._onBeforePhysicsObserver = null;
  90241. this._onAfterPhysicsObserver = null;
  90242. this._onAfterAnimationsObserver = null;
  90243. // Before render
  90244. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90245. if (_this._captureActiveMeshesEvaluationTime) {
  90246. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90247. }
  90248. if (_this._captureRenderTargetsRenderTime) {
  90249. _this._renderTargetsRenderTime.fetchNewFrame();
  90250. }
  90251. if (_this._captureFrameTime) {
  90252. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90253. _this._frameTime.beginMonitoring();
  90254. }
  90255. if (_this._captureInterFrameTime) {
  90256. _this._interFrameTime.endMonitoring();
  90257. }
  90258. if (_this._captureParticlesRenderTime) {
  90259. _this._particlesRenderTime.fetchNewFrame();
  90260. }
  90261. if (_this._captureSpritesRenderTime) {
  90262. _this._spritesRenderTime.fetchNewFrame();
  90263. }
  90264. if (_this._captureAnimationsTime) {
  90265. _this._animationsTime.beginMonitoring();
  90266. }
  90267. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90268. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90269. });
  90270. // After render
  90271. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90272. if (_this._captureFrameTime) {
  90273. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90274. _this._frameTime.endMonitoring();
  90275. }
  90276. if (_this._captureRenderTime) {
  90277. _this._renderTime.endMonitoring(false);
  90278. }
  90279. if (_this._captureInterFrameTime) {
  90280. _this._interFrameTime.beginMonitoring();
  90281. }
  90282. });
  90283. }
  90284. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90285. // Properties
  90286. /**
  90287. * Gets the perf counter used for active meshes evaluation time
  90288. */
  90289. get: function () {
  90290. return this._activeMeshesEvaluationTime;
  90291. },
  90292. enumerable: true,
  90293. configurable: true
  90294. });
  90295. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90296. /**
  90297. * Gets the active meshes evaluation time capture status
  90298. */
  90299. get: function () {
  90300. return this._captureActiveMeshesEvaluationTime;
  90301. },
  90302. /**
  90303. * Enable or disable the active meshes evaluation time capture
  90304. */
  90305. set: function (value) {
  90306. var _this = this;
  90307. if (value === this._captureActiveMeshesEvaluationTime) {
  90308. return;
  90309. }
  90310. this._captureActiveMeshesEvaluationTime = value;
  90311. if (value) {
  90312. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90313. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90314. _this._activeMeshesEvaluationTime.beginMonitoring();
  90315. });
  90316. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90317. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90318. _this._activeMeshesEvaluationTime.endMonitoring();
  90319. });
  90320. }
  90321. else {
  90322. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90323. this._onBeforeActiveMeshesEvaluationObserver = null;
  90324. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90325. this._onAfterActiveMeshesEvaluationObserver = null;
  90326. }
  90327. },
  90328. enumerable: true,
  90329. configurable: true
  90330. });
  90331. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90332. /**
  90333. * Gets the perf counter used for render targets render time
  90334. */
  90335. get: function () {
  90336. return this._renderTargetsRenderTime;
  90337. },
  90338. enumerable: true,
  90339. configurable: true
  90340. });
  90341. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90342. /**
  90343. * Gets the render targets render time capture status
  90344. */
  90345. get: function () {
  90346. return this._captureRenderTargetsRenderTime;
  90347. },
  90348. /**
  90349. * Enable or disable the render targets render time capture
  90350. */
  90351. set: function (value) {
  90352. var _this = this;
  90353. if (value === this._captureRenderTargetsRenderTime) {
  90354. return;
  90355. }
  90356. this._captureRenderTargetsRenderTime = value;
  90357. if (value) {
  90358. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90359. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90360. _this._renderTargetsRenderTime.beginMonitoring();
  90361. });
  90362. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90363. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90364. _this._renderTargetsRenderTime.endMonitoring(false);
  90365. });
  90366. }
  90367. else {
  90368. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90369. this._onBeforeRenderTargetsRenderObserver = null;
  90370. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90371. this._onAfterRenderTargetsRenderObserver = null;
  90372. }
  90373. },
  90374. enumerable: true,
  90375. configurable: true
  90376. });
  90377. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90378. /**
  90379. * Gets the perf counter used for particles render time
  90380. */
  90381. get: function () {
  90382. return this._particlesRenderTime;
  90383. },
  90384. enumerable: true,
  90385. configurable: true
  90386. });
  90387. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90388. /**
  90389. * Gets the particles render time capture status
  90390. */
  90391. get: function () {
  90392. return this._captureParticlesRenderTime;
  90393. },
  90394. /**
  90395. * Enable or disable the particles render time capture
  90396. */
  90397. set: function (value) {
  90398. var _this = this;
  90399. if (value === this._captureParticlesRenderTime) {
  90400. return;
  90401. }
  90402. this._captureParticlesRenderTime = value;
  90403. if (value) {
  90404. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90405. BABYLON.Tools.StartPerformanceCounter("Particles");
  90406. _this._particlesRenderTime.beginMonitoring();
  90407. });
  90408. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90409. BABYLON.Tools.EndPerformanceCounter("Particles");
  90410. _this._particlesRenderTime.endMonitoring(false);
  90411. });
  90412. }
  90413. else {
  90414. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90415. this._onBeforeParticlesRenderingObserver = null;
  90416. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90417. this._onAfterParticlesRenderingObserver = null;
  90418. }
  90419. },
  90420. enumerable: true,
  90421. configurable: true
  90422. });
  90423. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90424. /**
  90425. * Gets the perf counter used for sprites render time
  90426. */
  90427. get: function () {
  90428. return this._spritesRenderTime;
  90429. },
  90430. enumerable: true,
  90431. configurable: true
  90432. });
  90433. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90434. /**
  90435. * Gets the sprites render time capture status
  90436. */
  90437. get: function () {
  90438. return this._captureSpritesRenderTime;
  90439. },
  90440. /**
  90441. * Enable or disable the sprites render time capture
  90442. */
  90443. set: function (value) {
  90444. var _this = this;
  90445. if (value === this._captureSpritesRenderTime) {
  90446. return;
  90447. }
  90448. this._captureSpritesRenderTime = value;
  90449. if (value) {
  90450. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90451. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90452. _this._spritesRenderTime.beginMonitoring();
  90453. });
  90454. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90455. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90456. _this._spritesRenderTime.endMonitoring(false);
  90457. });
  90458. }
  90459. else {
  90460. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90461. this._onBeforeSpritesRenderingObserver = null;
  90462. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90463. this._onAfterSpritesRenderingObserver = null;
  90464. }
  90465. },
  90466. enumerable: true,
  90467. configurable: true
  90468. });
  90469. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90470. /**
  90471. * Gets the perf counter used for physics time
  90472. */
  90473. get: function () {
  90474. return this._physicsTime;
  90475. },
  90476. enumerable: true,
  90477. configurable: true
  90478. });
  90479. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90480. /**
  90481. * Gets the physics time capture status
  90482. */
  90483. get: function () {
  90484. return this._capturePhysicsTime;
  90485. },
  90486. /**
  90487. * Enable or disable the physics time capture
  90488. */
  90489. set: function (value) {
  90490. var _this = this;
  90491. if (value === this._capturePhysicsTime) {
  90492. return;
  90493. }
  90494. this._capturePhysicsTime = value;
  90495. if (value) {
  90496. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90497. BABYLON.Tools.StartPerformanceCounter("Physics");
  90498. _this._physicsTime.beginMonitoring();
  90499. });
  90500. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90501. BABYLON.Tools.EndPerformanceCounter("Physics");
  90502. _this._physicsTime.endMonitoring();
  90503. });
  90504. }
  90505. else {
  90506. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90507. this._onBeforePhysicsObserver = null;
  90508. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90509. this._onAfterPhysicsObserver = null;
  90510. }
  90511. },
  90512. enumerable: true,
  90513. configurable: true
  90514. });
  90515. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90516. /**
  90517. * Gets the perf counter used for animations time
  90518. */
  90519. get: function () {
  90520. return this._animationsTime;
  90521. },
  90522. enumerable: true,
  90523. configurable: true
  90524. });
  90525. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90526. /**
  90527. * Gets the animations time capture status
  90528. */
  90529. get: function () {
  90530. return this._captureAnimationsTime;
  90531. },
  90532. /**
  90533. * Enable or disable the animations time capture
  90534. */
  90535. set: function (value) {
  90536. var _this = this;
  90537. if (value === this._captureAnimationsTime) {
  90538. return;
  90539. }
  90540. this._captureAnimationsTime = value;
  90541. if (value) {
  90542. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90543. _this._animationsTime.endMonitoring();
  90544. });
  90545. }
  90546. else {
  90547. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90548. this._onAfterAnimationsObserver = null;
  90549. }
  90550. },
  90551. enumerable: true,
  90552. configurable: true
  90553. });
  90554. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90555. /**
  90556. * Gets the perf counter used for frame time capture
  90557. */
  90558. get: function () {
  90559. return this._frameTime;
  90560. },
  90561. enumerable: true,
  90562. configurable: true
  90563. });
  90564. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90565. /**
  90566. * Gets the frame time capture status
  90567. */
  90568. get: function () {
  90569. return this._captureFrameTime;
  90570. },
  90571. /**
  90572. * Enable or disable the frame time capture
  90573. */
  90574. set: function (value) {
  90575. this._captureFrameTime = value;
  90576. },
  90577. enumerable: true,
  90578. configurable: true
  90579. });
  90580. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90581. /**
  90582. * Gets the perf counter used for inter-frames time capture
  90583. */
  90584. get: function () {
  90585. return this._interFrameTime;
  90586. },
  90587. enumerable: true,
  90588. configurable: true
  90589. });
  90590. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90591. /**
  90592. * Gets the inter-frames time capture status
  90593. */
  90594. get: function () {
  90595. return this._captureInterFrameTime;
  90596. },
  90597. /**
  90598. * Enable or disable the inter-frames time capture
  90599. */
  90600. set: function (value) {
  90601. this._captureInterFrameTime = value;
  90602. },
  90603. enumerable: true,
  90604. configurable: true
  90605. });
  90606. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90607. /**
  90608. * Gets the perf counter used for render time capture
  90609. */
  90610. get: function () {
  90611. return this._renderTime;
  90612. },
  90613. enumerable: true,
  90614. configurable: true
  90615. });
  90616. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90617. /**
  90618. * Gets the render time capture status
  90619. */
  90620. get: function () {
  90621. return this._captureRenderTime;
  90622. },
  90623. /**
  90624. * Enable or disable the render time capture
  90625. */
  90626. set: function (value) {
  90627. var _this = this;
  90628. if (value === this._captureRenderTime) {
  90629. return;
  90630. }
  90631. this._captureRenderTime = value;
  90632. if (value) {
  90633. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90634. _this._renderTime.beginMonitoring();
  90635. BABYLON.Tools.StartPerformanceCounter("Main render");
  90636. });
  90637. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90638. _this._renderTime.endMonitoring(false);
  90639. BABYLON.Tools.EndPerformanceCounter("Main render");
  90640. });
  90641. }
  90642. else {
  90643. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90644. this._onBeforeDrawPhaseObserver = null;
  90645. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90646. this._onAfterDrawPhaseObserver = null;
  90647. }
  90648. },
  90649. enumerable: true,
  90650. configurable: true
  90651. });
  90652. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90653. /**
  90654. * Gets the perf counter used for draw calls
  90655. */
  90656. get: function () {
  90657. return this.scene.getEngine()._drawCalls;
  90658. },
  90659. enumerable: true,
  90660. configurable: true
  90661. });
  90662. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90663. /**
  90664. * Gets the perf counter used for texture collisions
  90665. */
  90666. get: function () {
  90667. return this.scene.getEngine()._textureCollisions;
  90668. },
  90669. enumerable: true,
  90670. configurable: true
  90671. });
  90672. SceneInstrumentation.prototype.dispose = function () {
  90673. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90674. this._onAfterRenderObserver = null;
  90675. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90676. this._onBeforeActiveMeshesEvaluationObserver = null;
  90677. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90678. this._onAfterActiveMeshesEvaluationObserver = null;
  90679. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90680. this._onBeforeRenderTargetsRenderObserver = null;
  90681. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90682. this._onAfterRenderTargetsRenderObserver = null;
  90683. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90684. this._onBeforeAnimationsObserver = null;
  90685. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90686. this._onBeforeParticlesRenderingObserver = null;
  90687. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90688. this._onAfterParticlesRenderingObserver = null;
  90689. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90690. this._onBeforeSpritesRenderingObserver = null;
  90691. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90692. this._onAfterSpritesRenderingObserver = null;
  90693. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90694. this._onBeforeDrawPhaseObserver = null;
  90695. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90696. this._onAfterDrawPhaseObserver = null;
  90697. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90698. this._onBeforePhysicsObserver = null;
  90699. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90700. this._onAfterPhysicsObserver = null;
  90701. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90702. this._onAfterAnimationsObserver = null;
  90703. this.scene = null;
  90704. };
  90705. return SceneInstrumentation;
  90706. }());
  90707. BABYLON.SceneInstrumentation = SceneInstrumentation;
  90708. })(BABYLON || (BABYLON = {}));
  90709. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  90710. "use strict";
  90711. var BABYLON;
  90712. (function (BABYLON) {
  90713. var _TimeToken = /** @class */ (function () {
  90714. function _TimeToken() {
  90715. this._timeElapsedQueryEnded = false;
  90716. }
  90717. return _TimeToken;
  90718. }());
  90719. BABYLON._TimeToken = _TimeToken;
  90720. })(BABYLON || (BABYLON = {}));
  90721. //# sourceMappingURL=babylon.timeToken.js.map
  90722. "use strict";
  90723. var BABYLON;
  90724. (function (BABYLON) {
  90725. /**
  90726. * Background material defines definition.
  90727. * @ignore Mainly internal Use
  90728. */
  90729. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  90730. __extends(BackgroundMaterialDefines, _super);
  90731. /**
  90732. * Constructor of the defines.
  90733. */
  90734. function BackgroundMaterialDefines() {
  90735. var _this = _super.call(this) || this;
  90736. /**
  90737. * True if the diffuse texture is in use.
  90738. */
  90739. _this.DIFFUSE = false;
  90740. /**
  90741. * The direct UV channel to use.
  90742. */
  90743. _this.DIFFUSEDIRECTUV = 0;
  90744. /**
  90745. * True if the diffuse texture is in gamma space.
  90746. */
  90747. _this.GAMMADIFFUSE = false;
  90748. /**
  90749. * True if the diffuse texture has opacity in the alpha channel.
  90750. */
  90751. _this.DIFFUSEHASALPHA = false;
  90752. /**
  90753. * True if you want the material to fade to transparent at grazing angle.
  90754. */
  90755. _this.OPACITYFRESNEL = false;
  90756. /**
  90757. * True if an extra blur needs to be added in the reflection.
  90758. */
  90759. _this.REFLECTIONBLUR = false;
  90760. /**
  90761. * True if you want the material to fade to reflection at grazing angle.
  90762. */
  90763. _this.REFLECTIONFRESNEL = false;
  90764. /**
  90765. * True if you want the material to falloff as far as you move away from the scene center.
  90766. */
  90767. _this.REFLECTIONFALLOFF = false;
  90768. /**
  90769. * False if the current Webgl implementation does not support the texture lod extension.
  90770. */
  90771. _this.TEXTURELODSUPPORT = false;
  90772. /**
  90773. * True to ensure the data are premultiplied.
  90774. */
  90775. _this.PREMULTIPLYALPHA = false;
  90776. /**
  90777. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  90778. */
  90779. _this.USERGBCOLOR = false;
  90780. /**
  90781. * True to add noise in order to reduce the banding effect.
  90782. */
  90783. _this.NOISE = false;
  90784. /**
  90785. * is the reflection texture in BGR color scheme?
  90786. * Mainly used to solve a bug in ios10 video tag
  90787. */
  90788. _this.REFLECTIONBGR = false;
  90789. _this.IMAGEPROCESSING = false;
  90790. _this.VIGNETTE = false;
  90791. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  90792. _this.VIGNETTEBLENDMODEOPAQUE = false;
  90793. _this.TONEMAPPING = false;
  90794. _this.CONTRAST = false;
  90795. _this.COLORCURVES = false;
  90796. _this.COLORGRADING = false;
  90797. _this.COLORGRADING3D = false;
  90798. _this.SAMPLER3DGREENDEPTH = false;
  90799. _this.SAMPLER3DBGRMAP = false;
  90800. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  90801. _this.EXPOSURE = false;
  90802. _this.GRAIN = false;
  90803. // Reflection.
  90804. _this.REFLECTION = false;
  90805. _this.REFLECTIONMAP_3D = false;
  90806. _this.REFLECTIONMAP_SPHERICAL = false;
  90807. _this.REFLECTIONMAP_PLANAR = false;
  90808. _this.REFLECTIONMAP_CUBIC = false;
  90809. _this.REFLECTIONMAP_PROJECTION = false;
  90810. _this.REFLECTIONMAP_SKYBOX = false;
  90811. _this.REFLECTIONMAP_EXPLICIT = false;
  90812. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90813. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90814. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90815. _this.INVERTCUBICMAP = false;
  90816. _this.REFLECTIONMAP_OPPOSITEZ = false;
  90817. _this.LODINREFLECTIONALPHA = false;
  90818. _this.GAMMAREFLECTION = false;
  90819. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  90820. // Default BJS.
  90821. _this.MAINUV1 = false;
  90822. _this.MAINUV2 = false;
  90823. _this.UV1 = false;
  90824. _this.UV2 = false;
  90825. _this.CLIPPLANE = false;
  90826. _this.POINTSIZE = false;
  90827. _this.FOG = false;
  90828. _this.NORMAL = false;
  90829. _this.NUM_BONE_INFLUENCERS = 0;
  90830. _this.BonesPerMesh = 0;
  90831. _this.INSTANCES = false;
  90832. _this.SHADOWFLOAT = false;
  90833. _this.rebuild();
  90834. return _this;
  90835. }
  90836. return BackgroundMaterialDefines;
  90837. }(BABYLON.MaterialDefines));
  90838. /**
  90839. * Background material used to create an efficient environement around your scene.
  90840. */
  90841. var BackgroundMaterial = /** @class */ (function (_super) {
  90842. __extends(BackgroundMaterial, _super);
  90843. /**
  90844. * Instantiates a Background Material in the given scene
  90845. * @param name The friendly name of the material
  90846. * @param scene The scene to add the material to
  90847. */
  90848. function BackgroundMaterial(name, scene) {
  90849. var _this = _super.call(this, name, scene) || this;
  90850. /**
  90851. * Key light Color (multiply against the R channel of the environement texture)
  90852. */
  90853. _this.primaryColor = BABYLON.Color3.White();
  90854. /**
  90855. * Key light Level (allowing HDR output of the background)
  90856. */
  90857. _this.primaryLevel = 1;
  90858. /**
  90859. * Secondary light Color (multiply against the G channel of the environement texture)
  90860. */
  90861. _this.secondaryColor = BABYLON.Color3.Gray();
  90862. /**
  90863. * Secondary light Level (allowing HDR output of the background)
  90864. */
  90865. _this.secondaryLevel = 1;
  90866. /**
  90867. * Tertiary light Color (multiply against the B channel of the environement texture)
  90868. */
  90869. _this.tertiaryColor = BABYLON.Color3.Black();
  90870. /**
  90871. * Tertiary light Level (allowing HDR output of the background)
  90872. */
  90873. _this.tertiaryLevel = 1;
  90874. /**
  90875. * Reflection Texture used in the material.
  90876. * Should be author in a specific way for the best result (refer to the documentation).
  90877. */
  90878. _this.reflectionTexture = null;
  90879. /**
  90880. * Reflection Texture level of blur.
  90881. *
  90882. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  90883. * texture twice.
  90884. */
  90885. _this.reflectionBlur = 0;
  90886. /**
  90887. * Diffuse Texture used in the material.
  90888. * Should be author in a specific way for the best result (refer to the documentation).
  90889. */
  90890. _this.diffuseTexture = null;
  90891. _this._shadowLights = null;
  90892. /**
  90893. * Specify the list of lights casting shadow on the material.
  90894. * All scene shadow lights will be included if null.
  90895. */
  90896. _this.shadowLights = null;
  90897. /**
  90898. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  90899. * soft lighting on the background.
  90900. */
  90901. _this.shadowBlurScale = 1;
  90902. /**
  90903. * Helps adjusting the shadow to a softer level if required.
  90904. * 0 means black shadows and 1 means no shadows.
  90905. */
  90906. _this.shadowLevel = 0;
  90907. /**
  90908. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  90909. * It is usually zero but might be interesting to modify according to your setup.
  90910. */
  90911. _this.sceneCenter = BABYLON.Vector3.Zero();
  90912. /**
  90913. * This helps specifying that the material is falling off to the sky box at grazing angle.
  90914. * This helps ensuring a nice transition when the camera goes under the ground.
  90915. */
  90916. _this.opacityFresnel = true;
  90917. /**
  90918. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  90919. * This helps adding a mirror texture on the ground.
  90920. */
  90921. _this.reflectionFresnel = false;
  90922. /**
  90923. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  90924. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  90925. */
  90926. _this.reflectionFalloffDistance = 0.0;
  90927. /**
  90928. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  90929. */
  90930. _this.reflectionAmount = 1.0;
  90931. /**
  90932. * This specifies the weight of the reflection at grazing angle.
  90933. */
  90934. _this.reflectionReflectance0 = 0.05;
  90935. /**
  90936. * This specifies the weight of the reflection at a perpendicular point of view.
  90937. */
  90938. _this.reflectionReflectance90 = 0.5;
  90939. /**
  90940. * Helps to directly use the maps channels instead of their level.
  90941. */
  90942. _this.useRGBColor = true;
  90943. /**
  90944. * This helps reducing the banding effect that could occur on the background.
  90945. */
  90946. _this.enableNoise = false;
  90947. _this._fovMultiplier = 1.0;
  90948. /**
  90949. * Enable the FOV adjustment feature controlled by fovMultiplier.
  90950. * @type {boolean}
  90951. */
  90952. _this.useEquirectangularFOV = false;
  90953. _this._maxSimultaneousLights = 4;
  90954. /**
  90955. * Number of Simultaneous lights allowed on the material.
  90956. */
  90957. _this.maxSimultaneousLights = 4;
  90958. /**
  90959. * Keep track of the image processing observer to allow dispose and replace.
  90960. */
  90961. _this._imageProcessingObserver = null;
  90962. /**
  90963. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  90964. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  90965. */
  90966. _this.switchToBGR = false;
  90967. // Temp values kept as cache in the material.
  90968. _this._renderTargets = new BABYLON.SmartArray(16);
  90969. _this._reflectionControls = BABYLON.Vector4.Zero();
  90970. // Setup the default processing configuration to the scene.
  90971. _this._attachImageProcessingConfiguration(null);
  90972. _this.getRenderTargetTextures = function () {
  90973. _this._renderTargets.reset();
  90974. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  90975. _this._renderTargets.push(_this._diffuseTexture);
  90976. }
  90977. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  90978. _this._renderTargets.push(_this._reflectionTexture);
  90979. }
  90980. return _this._renderTargets;
  90981. };
  90982. return _this;
  90983. }
  90984. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  90985. /**
  90986. * Sets the reflection reflectance fresnel values according to the default standard
  90987. * empirically know to work well :-)
  90988. */
  90989. set: function (value) {
  90990. var reflectionWeight = value;
  90991. if (reflectionWeight < 0.5) {
  90992. reflectionWeight = reflectionWeight * 2.0;
  90993. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  90994. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  90995. }
  90996. else {
  90997. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  90998. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  90999. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  91000. }
  91001. },
  91002. enumerable: true,
  91003. configurable: true
  91004. });
  91005. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  91006. /**
  91007. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91008. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  91009. * Recommended to be keep at 1.0 except for special cases.
  91010. */
  91011. get: function () {
  91012. return this._fovMultiplier;
  91013. },
  91014. set: function (value) {
  91015. if (isNaN(value)) {
  91016. value = 1.0;
  91017. }
  91018. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  91019. },
  91020. enumerable: true,
  91021. configurable: true
  91022. });
  91023. /**
  91024. * Attaches a new image processing configuration to the PBR Material.
  91025. * @param configuration (if null the scene configuration will be use)
  91026. */
  91027. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  91028. var _this = this;
  91029. if (configuration === this._imageProcessingConfiguration) {
  91030. return;
  91031. }
  91032. // Detaches observer.
  91033. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91034. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91035. }
  91036. // Pick the scene configuration if needed.
  91037. if (!configuration) {
  91038. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91039. }
  91040. else {
  91041. this._imageProcessingConfiguration = configuration;
  91042. }
  91043. // Attaches observer.
  91044. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91045. _this._markAllSubMeshesAsImageProcessingDirty();
  91046. });
  91047. };
  91048. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91049. /**
  91050. * Gets the image processing configuration used either in this material.
  91051. */
  91052. get: function () {
  91053. return this._imageProcessingConfiguration;
  91054. },
  91055. /**
  91056. * Sets the Default image processing configuration used either in the this material.
  91057. *
  91058. * If sets to null, the scene one is in use.
  91059. */
  91060. set: function (value) {
  91061. this._attachImageProcessingConfiguration(value);
  91062. // Ensure the effect will be rebuilt.
  91063. this._markAllSubMeshesAsTexturesDirty();
  91064. },
  91065. enumerable: true,
  91066. configurable: true
  91067. });
  91068. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91069. /**
  91070. * Gets wether the color curves effect is enabled.
  91071. */
  91072. get: function () {
  91073. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91074. },
  91075. /**
  91076. * Sets wether the color curves effect is enabled.
  91077. */
  91078. set: function (value) {
  91079. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91080. },
  91081. enumerable: true,
  91082. configurable: true
  91083. });
  91084. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91085. /**
  91086. * Gets wether the color grading effect is enabled.
  91087. */
  91088. get: function () {
  91089. return this.imageProcessingConfiguration.colorGradingEnabled;
  91090. },
  91091. /**
  91092. * Gets wether the color grading effect is enabled.
  91093. */
  91094. set: function (value) {
  91095. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91096. },
  91097. enumerable: true,
  91098. configurable: true
  91099. });
  91100. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91101. /**
  91102. * Gets wether tonemapping is enabled or not.
  91103. */
  91104. get: function () {
  91105. return this._imageProcessingConfiguration.toneMappingEnabled;
  91106. },
  91107. /**
  91108. * Sets wether tonemapping is enabled or not
  91109. */
  91110. set: function (value) {
  91111. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91112. },
  91113. enumerable: true,
  91114. configurable: true
  91115. });
  91116. ;
  91117. ;
  91118. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91119. /**
  91120. * The camera exposure used on this material.
  91121. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91122. * This corresponds to a photographic exposure.
  91123. */
  91124. get: function () {
  91125. return this._imageProcessingConfiguration.exposure;
  91126. },
  91127. /**
  91128. * The camera exposure used on this material.
  91129. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91130. * This corresponds to a photographic exposure.
  91131. */
  91132. set: function (value) {
  91133. this._imageProcessingConfiguration.exposure = value;
  91134. },
  91135. enumerable: true,
  91136. configurable: true
  91137. });
  91138. ;
  91139. ;
  91140. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91141. /**
  91142. * Gets The camera contrast used on this material.
  91143. */
  91144. get: function () {
  91145. return this._imageProcessingConfiguration.contrast;
  91146. },
  91147. /**
  91148. * Sets The camera contrast used on this material.
  91149. */
  91150. set: function (value) {
  91151. this._imageProcessingConfiguration.contrast = value;
  91152. },
  91153. enumerable: true,
  91154. configurable: true
  91155. });
  91156. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91157. /**
  91158. * Gets the Color Grading 2D Lookup Texture.
  91159. */
  91160. get: function () {
  91161. return this._imageProcessingConfiguration.colorGradingTexture;
  91162. },
  91163. /**
  91164. * Sets the Color Grading 2D Lookup Texture.
  91165. */
  91166. set: function (value) {
  91167. this.imageProcessingConfiguration.colorGradingTexture = value;
  91168. },
  91169. enumerable: true,
  91170. configurable: true
  91171. });
  91172. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91173. /**
  91174. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91175. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91176. * 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;
  91177. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91178. */
  91179. get: function () {
  91180. return this.imageProcessingConfiguration.colorCurves;
  91181. },
  91182. /**
  91183. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91184. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91185. * 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;
  91186. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91187. */
  91188. set: function (value) {
  91189. this.imageProcessingConfiguration.colorCurves = value;
  91190. },
  91191. enumerable: true,
  91192. configurable: true
  91193. });
  91194. /**
  91195. * The entire material has been created in order to prevent overdraw.
  91196. * @returns false
  91197. */
  91198. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91199. return true;
  91200. };
  91201. /**
  91202. * The entire material has been created in order to prevent overdraw.
  91203. * @returns true if blending is enable
  91204. */
  91205. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91206. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91207. };
  91208. /**
  91209. * Checks wether the material is ready to be rendered for a given mesh.
  91210. * @param mesh The mesh to render
  91211. * @param subMesh The submesh to check against
  91212. * @param useInstances Specify wether or not the material is used with instances
  91213. * @returns true if all the dependencies are ready (Textures, Effects...)
  91214. */
  91215. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91216. var _this = this;
  91217. if (useInstances === void 0) { useInstances = false; }
  91218. if (subMesh.effect && this.isFrozen) {
  91219. if (this._wasPreviouslyReady) {
  91220. return true;
  91221. }
  91222. }
  91223. if (!subMesh._materialDefines) {
  91224. subMesh._materialDefines = new BackgroundMaterialDefines();
  91225. }
  91226. var scene = this.getScene();
  91227. var defines = subMesh._materialDefines;
  91228. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91229. if (defines._renderId === scene.getRenderId()) {
  91230. return true;
  91231. }
  91232. }
  91233. var engine = scene.getEngine();
  91234. // Lights
  91235. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91236. defines._needNormals = true;
  91237. // Textures
  91238. if (defines._areTexturesDirty) {
  91239. defines._needUVs = false;
  91240. if (scene.texturesEnabled) {
  91241. if (scene.getEngine().getCaps().textureLOD) {
  91242. defines.TEXTURELODSUPPORT = true;
  91243. }
  91244. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91245. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91246. return false;
  91247. }
  91248. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91249. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91250. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91251. defines.OPACITYFRESNEL = this._opacityFresnel;
  91252. }
  91253. else {
  91254. defines.DIFFUSE = false;
  91255. defines.DIFFUSEHASALPHA = false;
  91256. defines.GAMMADIFFUSE = false;
  91257. defines.OPACITYFRESNEL = false;
  91258. }
  91259. var reflectionTexture = this._reflectionTexture;
  91260. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91261. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91262. return false;
  91263. }
  91264. defines.REFLECTION = true;
  91265. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91266. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91267. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91268. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91269. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91270. defines.REFLECTIONBGR = this.switchToBGR;
  91271. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91272. defines.INVERTCUBICMAP = true;
  91273. }
  91274. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91275. switch (reflectionTexture.coordinatesMode) {
  91276. case BABYLON.Texture.CUBIC_MODE:
  91277. case BABYLON.Texture.INVCUBIC_MODE:
  91278. defines.REFLECTIONMAP_CUBIC = true;
  91279. break;
  91280. case BABYLON.Texture.EXPLICIT_MODE:
  91281. defines.REFLECTIONMAP_EXPLICIT = true;
  91282. break;
  91283. case BABYLON.Texture.PLANAR_MODE:
  91284. defines.REFLECTIONMAP_PLANAR = true;
  91285. break;
  91286. case BABYLON.Texture.PROJECTION_MODE:
  91287. defines.REFLECTIONMAP_PROJECTION = true;
  91288. break;
  91289. case BABYLON.Texture.SKYBOX_MODE:
  91290. defines.REFLECTIONMAP_SKYBOX = true;
  91291. break;
  91292. case BABYLON.Texture.SPHERICAL_MODE:
  91293. defines.REFLECTIONMAP_SPHERICAL = true;
  91294. break;
  91295. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91296. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91297. break;
  91298. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91299. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91300. break;
  91301. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91302. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91303. break;
  91304. }
  91305. if (this.reflectionFresnel) {
  91306. defines.REFLECTIONFRESNEL = true;
  91307. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91308. this._reflectionControls.x = this.reflectionAmount;
  91309. this._reflectionControls.y = this.reflectionReflectance0;
  91310. this._reflectionControls.z = this.reflectionReflectance90;
  91311. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91312. }
  91313. else {
  91314. defines.REFLECTIONFRESNEL = false;
  91315. defines.REFLECTIONFALLOFF = false;
  91316. }
  91317. }
  91318. else {
  91319. defines.REFLECTION = false;
  91320. defines.REFLECTIONFALLOFF = false;
  91321. defines.REFLECTIONBLUR = false;
  91322. defines.REFLECTIONMAP_3D = false;
  91323. defines.REFLECTIONMAP_SPHERICAL = false;
  91324. defines.REFLECTIONMAP_PLANAR = false;
  91325. defines.REFLECTIONMAP_CUBIC = false;
  91326. defines.REFLECTIONMAP_PROJECTION = false;
  91327. defines.REFLECTIONMAP_SKYBOX = false;
  91328. defines.REFLECTIONMAP_EXPLICIT = false;
  91329. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91330. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91331. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91332. defines.INVERTCUBICMAP = false;
  91333. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91334. defines.LODINREFLECTIONALPHA = false;
  91335. defines.GAMMAREFLECTION = false;
  91336. }
  91337. }
  91338. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91339. defines.USERGBCOLOR = this._useRGBColor;
  91340. defines.NOISE = this._enableNoise;
  91341. }
  91342. if (defines._areImageProcessingDirty) {
  91343. if (!this._imageProcessingConfiguration.isReady()) {
  91344. return false;
  91345. }
  91346. this._imageProcessingConfiguration.prepareDefines(defines);
  91347. }
  91348. // Misc.
  91349. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91350. // Values that need to be evaluated on every frame
  91351. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91352. // Attribs
  91353. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91354. if (mesh) {
  91355. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91356. mesh.createNormals(true);
  91357. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91358. }
  91359. }
  91360. }
  91361. // Get correct effect
  91362. if (defines.isDirty) {
  91363. defines.markAsProcessed();
  91364. scene.resetCachedMaterial();
  91365. // Fallbacks
  91366. var fallbacks = new BABYLON.EffectFallbacks();
  91367. if (defines.FOG) {
  91368. fallbacks.addFallback(0, "FOG");
  91369. }
  91370. if (defines.POINTSIZE) {
  91371. fallbacks.addFallback(1, "POINTSIZE");
  91372. }
  91373. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91374. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91375. fallbacks.addCPUSkinningFallback(0, mesh);
  91376. }
  91377. //Attributes
  91378. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91379. if (defines.NORMAL) {
  91380. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91381. }
  91382. if (defines.UV1) {
  91383. attribs.push(BABYLON.VertexBuffer.UVKind);
  91384. }
  91385. if (defines.UV2) {
  91386. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91387. }
  91388. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91389. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91390. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91391. "vFogInfos", "vFogColor", "pointSize",
  91392. "vClipPlane", "mBones",
  91393. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91394. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91395. "shadowLevel", "alpha",
  91396. "vBackgroundCenter", "vReflectionControl",
  91397. "vDiffuseInfos", "diffuseMatrix",
  91398. ];
  91399. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91400. var uniformBuffers = ["Material", "Scene"];
  91401. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91402. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91403. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91404. uniformsNames: uniforms,
  91405. uniformBuffersNames: uniformBuffers,
  91406. samplers: samplers,
  91407. defines: defines,
  91408. maxSimultaneousLights: this._maxSimultaneousLights
  91409. });
  91410. var onCompiled = function (effect) {
  91411. if (_this.onCompiled) {
  91412. _this.onCompiled(effect);
  91413. }
  91414. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91415. };
  91416. var join = defines.toString();
  91417. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91418. attributes: attribs,
  91419. uniformsNames: uniforms,
  91420. uniformBuffersNames: uniformBuffers,
  91421. samplers: samplers,
  91422. defines: join,
  91423. fallbacks: fallbacks,
  91424. onCompiled: onCompiled,
  91425. onError: this.onError,
  91426. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91427. }, engine), defines);
  91428. this.buildUniformLayout();
  91429. }
  91430. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91431. return false;
  91432. }
  91433. defines._renderId = scene.getRenderId();
  91434. this._wasPreviouslyReady = true;
  91435. return true;
  91436. };
  91437. /**
  91438. * Build the uniform buffer used in the material.
  91439. */
  91440. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91441. // Order is important !
  91442. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91443. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91444. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91445. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91446. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91447. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91448. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91449. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91450. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91451. this._uniformBuffer.addUniform("pointSize", 1);
  91452. this._uniformBuffer.addUniform("shadowLevel", 1);
  91453. this._uniformBuffer.addUniform("alpha", 1);
  91454. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91455. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91456. this._uniformBuffer.create();
  91457. };
  91458. /**
  91459. * Unbind the material.
  91460. */
  91461. BackgroundMaterial.prototype.unbind = function () {
  91462. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91463. this._uniformBuffer.setTexture("diffuseSampler", null);
  91464. }
  91465. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91466. this._uniformBuffer.setTexture("reflectionSampler", null);
  91467. }
  91468. _super.prototype.unbind.call(this);
  91469. };
  91470. /**
  91471. * Bind only the world matrix to the material.
  91472. * @param world The world matrix to bind.
  91473. */
  91474. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91475. this._activeEffect.setMatrix("world", world);
  91476. };
  91477. /**
  91478. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91479. * @param world The world matrix to bind.
  91480. * @param subMesh The submesh to bind for.
  91481. */
  91482. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91483. var scene = this.getScene();
  91484. var defines = subMesh._materialDefines;
  91485. if (!defines) {
  91486. return;
  91487. }
  91488. var effect = subMesh.effect;
  91489. if (!effect) {
  91490. return;
  91491. }
  91492. this._activeEffect = effect;
  91493. // Matrices
  91494. this.bindOnlyWorldMatrix(world);
  91495. // Bones
  91496. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91497. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91498. if (mustRebind) {
  91499. this._uniformBuffer.bindToEffect(effect, "Material");
  91500. this.bindViewProjection(effect);
  91501. var reflectionTexture = this._reflectionTexture;
  91502. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91503. // Texture uniforms
  91504. if (scene.texturesEnabled) {
  91505. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91506. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91507. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91508. }
  91509. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91510. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91511. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91512. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91513. }
  91514. }
  91515. if (this.shadowLevel > 0) {
  91516. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91517. }
  91518. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91519. // Point size
  91520. if (this.pointsCloud) {
  91521. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91522. }
  91523. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91524. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91525. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91526. }
  91527. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91528. // Textures
  91529. if (scene.texturesEnabled) {
  91530. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91531. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91532. }
  91533. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91534. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91535. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91536. }
  91537. else if (!defines.REFLECTIONBLUR) {
  91538. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91539. }
  91540. else {
  91541. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91542. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91543. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91544. }
  91545. if (defines.REFLECTIONFRESNEL) {
  91546. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91547. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91548. }
  91549. }
  91550. }
  91551. // Clip plane
  91552. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91553. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91554. }
  91555. if (mustRebind || !this.isFrozen) {
  91556. if (scene.lightsEnabled) {
  91557. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91558. }
  91559. // View
  91560. this.bindView(effect);
  91561. // Fog
  91562. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91563. // image processing
  91564. this._imageProcessingConfiguration.bind(this._activeEffect);
  91565. }
  91566. this._uniformBuffer.update();
  91567. this._afterBind(mesh);
  91568. };
  91569. /**
  91570. * Dispose the material.
  91571. * @param forceDisposeEffect Force disposal of the associated effect.
  91572. * @param forceDisposeTextures Force disposal of the associated textures.
  91573. */
  91574. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91575. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91576. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91577. if (forceDisposeTextures) {
  91578. if (this.diffuseTexture) {
  91579. this.diffuseTexture.dispose();
  91580. }
  91581. if (this.reflectionTexture) {
  91582. this.reflectionTexture.dispose();
  91583. }
  91584. }
  91585. this._renderTargets.dispose();
  91586. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91587. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91588. }
  91589. _super.prototype.dispose.call(this, forceDisposeEffect);
  91590. };
  91591. /**
  91592. * Clones the material.
  91593. * @param name The cloned name.
  91594. * @returns The cloned material.
  91595. */
  91596. BackgroundMaterial.prototype.clone = function (name) {
  91597. var _this = this;
  91598. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91599. };
  91600. /**
  91601. * Serializes the current material to its JSON representation.
  91602. * @returns The JSON representation.
  91603. */
  91604. BackgroundMaterial.prototype.serialize = function () {
  91605. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91606. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91607. return serializationObject;
  91608. };
  91609. /**
  91610. * Gets the class name of the material
  91611. * @returns "BackgroundMaterial"
  91612. */
  91613. BackgroundMaterial.prototype.getClassName = function () {
  91614. return "BackgroundMaterial";
  91615. };
  91616. /**
  91617. * Parse a JSON input to create back a background material.
  91618. * @param source The JSON data to parse
  91619. * @param scene The scene to create the parsed material in
  91620. * @param rootUrl The root url of the assets the material depends upon
  91621. * @returns the instantiated BackgroundMaterial.
  91622. */
  91623. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91624. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91625. };
  91626. /**
  91627. * Standard reflectance value at parallel view angle.
  91628. */
  91629. BackgroundMaterial.StandardReflectance0 = 0.05;
  91630. /**
  91631. * Standard reflectance value at grazing angle.
  91632. */
  91633. BackgroundMaterial.StandardReflectance90 = 0.5;
  91634. __decorate([
  91635. BABYLON.serializeAsColor3()
  91636. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91637. __decorate([
  91638. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91639. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91640. __decorate([
  91641. BABYLON.serialize()
  91642. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91643. __decorate([
  91644. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91645. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91646. __decorate([
  91647. BABYLON.serializeAsColor3()
  91648. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91649. __decorate([
  91650. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91651. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91652. __decorate([
  91653. BABYLON.serialize()
  91654. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91655. __decorate([
  91656. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91657. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91658. __decorate([
  91659. BABYLON.serializeAsColor3()
  91660. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91661. __decorate([
  91662. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91663. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91664. __decorate([
  91665. BABYLON.serialize()
  91666. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91667. __decorate([
  91668. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91669. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91670. __decorate([
  91671. BABYLON.serializeAsTexture()
  91672. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91673. __decorate([
  91674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91675. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91676. __decorate([
  91677. BABYLON.serialize()
  91678. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91679. __decorate([
  91680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91681. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91682. __decorate([
  91683. BABYLON.serializeAsTexture()
  91684. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91685. __decorate([
  91686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91687. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  91688. __decorate([
  91689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91690. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  91691. __decorate([
  91692. BABYLON.serialize()
  91693. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  91694. __decorate([
  91695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91696. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  91697. __decorate([
  91698. BABYLON.serialize()
  91699. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  91700. __decorate([
  91701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91702. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  91703. __decorate([
  91704. BABYLON.serializeAsVector3()
  91705. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  91706. __decorate([
  91707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91708. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  91709. __decorate([
  91710. BABYLON.serialize()
  91711. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  91712. __decorate([
  91713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91714. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  91715. __decorate([
  91716. BABYLON.serialize()
  91717. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  91718. __decorate([
  91719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91720. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  91721. __decorate([
  91722. BABYLON.serialize()
  91723. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  91724. __decorate([
  91725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91726. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  91727. __decorate([
  91728. BABYLON.serialize()
  91729. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  91730. __decorate([
  91731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91732. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  91733. __decorate([
  91734. BABYLON.serialize()
  91735. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  91736. __decorate([
  91737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91738. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  91739. __decorate([
  91740. BABYLON.serialize()
  91741. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  91742. __decorate([
  91743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91744. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  91745. __decorate([
  91746. BABYLON.serialize()
  91747. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  91748. __decorate([
  91749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91750. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  91751. __decorate([
  91752. BABYLON.serialize()
  91753. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  91754. __decorate([
  91755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91756. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  91757. __decorate([
  91758. BABYLON.serialize()
  91759. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  91760. __decorate([
  91761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91762. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  91763. __decorate([
  91764. BABYLON.serializeAsImageProcessingConfiguration()
  91765. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  91766. return BackgroundMaterial;
  91767. }(BABYLON.PushMaterial));
  91768. BABYLON.BackgroundMaterial = BackgroundMaterial;
  91769. })(BABYLON || (BABYLON = {}));
  91770. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  91771. "use strict";
  91772. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91773. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91774. s = arguments[i];
  91775. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91776. t[p] = s[p];
  91777. }
  91778. return t;
  91779. };
  91780. var BABYLON;
  91781. (function (BABYLON) {
  91782. /**
  91783. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  91784. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  91785. * It also helps with the default setup of your imageProcessing configuration.
  91786. */
  91787. var EnvironmentHelper = /** @class */ (function () {
  91788. /**
  91789. * constructor
  91790. * @param options
  91791. * @param scene The scene to add the material to
  91792. */
  91793. function EnvironmentHelper(options, scene) {
  91794. var _this = this;
  91795. this._errorHandler = function (message, exception) {
  91796. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  91797. };
  91798. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  91799. this._scene = scene;
  91800. this.onErrorObservable = new BABYLON.Observable();
  91801. this._setupBackground();
  91802. this._setupImageProcessing();
  91803. }
  91804. /**
  91805. * Creates the default options for the helper.
  91806. */
  91807. EnvironmentHelper._getDefaultOptions = function () {
  91808. return {
  91809. createGround: true,
  91810. groundSize: 15,
  91811. groundTexture: this._groundTextureCDNUrl,
  91812. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91813. groundOpacity: 0.9,
  91814. enableGroundShadow: true,
  91815. groundShadowLevel: 0.5,
  91816. enableGroundMirror: false,
  91817. groundMirrorSizeRatio: 0.3,
  91818. groundMirrorBlurKernel: 64,
  91819. groundMirrorAmount: 1,
  91820. groundMirrorFresnelWeight: 1,
  91821. groundMirrorFallOffDistance: 0,
  91822. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  91823. groundYBias: 0.00001,
  91824. createSkybox: true,
  91825. skyboxSize: 20,
  91826. skyboxTexture: this._skyboxTextureCDNUrl,
  91827. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91828. backgroundYRotation: 0,
  91829. sizeAuto: true,
  91830. rootPosition: BABYLON.Vector3.Zero(),
  91831. setupImageProcessing: true,
  91832. environmentTexture: this._environmentTextureCDNUrl,
  91833. cameraExposure: 0.8,
  91834. cameraContrast: 1.2,
  91835. toneMappingEnabled: true,
  91836. };
  91837. };
  91838. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  91839. /**
  91840. * Gets the root mesh created by the helper.
  91841. */
  91842. get: function () {
  91843. return this._rootMesh;
  91844. },
  91845. enumerable: true,
  91846. configurable: true
  91847. });
  91848. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  91849. /**
  91850. * Gets the skybox created by the helper.
  91851. */
  91852. get: function () {
  91853. return this._skybox;
  91854. },
  91855. enumerable: true,
  91856. configurable: true
  91857. });
  91858. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  91859. /**
  91860. * Gets the skybox texture created by the helper.
  91861. */
  91862. get: function () {
  91863. return this._skyboxTexture;
  91864. },
  91865. enumerable: true,
  91866. configurable: true
  91867. });
  91868. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  91869. /**
  91870. * Gets the skybox material created by the helper.
  91871. */
  91872. get: function () {
  91873. return this._skyboxMaterial;
  91874. },
  91875. enumerable: true,
  91876. configurable: true
  91877. });
  91878. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  91879. /**
  91880. * Gets the ground mesh created by the helper.
  91881. */
  91882. get: function () {
  91883. return this._ground;
  91884. },
  91885. enumerable: true,
  91886. configurable: true
  91887. });
  91888. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  91889. /**
  91890. * Gets the ground texture created by the helper.
  91891. */
  91892. get: function () {
  91893. return this._groundTexture;
  91894. },
  91895. enumerable: true,
  91896. configurable: true
  91897. });
  91898. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  91899. /**
  91900. * Gets the ground mirror created by the helper.
  91901. */
  91902. get: function () {
  91903. return this._groundMirror;
  91904. },
  91905. enumerable: true,
  91906. configurable: true
  91907. });
  91908. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  91909. /**
  91910. * Gets the ground mirror render list to helps pushing the meshes
  91911. * you wish in the ground reflection.
  91912. */
  91913. get: function () {
  91914. if (this._groundMirror) {
  91915. return this._groundMirror.renderList;
  91916. }
  91917. return null;
  91918. },
  91919. enumerable: true,
  91920. configurable: true
  91921. });
  91922. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  91923. /**
  91924. * Gets the ground material created by the helper.
  91925. */
  91926. get: function () {
  91927. return this._groundMaterial;
  91928. },
  91929. enumerable: true,
  91930. configurable: true
  91931. });
  91932. /**
  91933. * Updates the background according to the new options
  91934. * @param options
  91935. */
  91936. EnvironmentHelper.prototype.updateOptions = function (options) {
  91937. var newOptions = __assign({}, this._options, options);
  91938. if (this._ground && !newOptions.createGround) {
  91939. this._ground.dispose();
  91940. this._ground = null;
  91941. }
  91942. if (this._groundMaterial && !newOptions.createGround) {
  91943. this._groundMaterial.dispose();
  91944. this._groundMaterial = null;
  91945. }
  91946. if (this._groundTexture) {
  91947. if (this._options.groundTexture != newOptions.groundTexture) {
  91948. this._groundTexture.dispose();
  91949. this._groundTexture = null;
  91950. }
  91951. }
  91952. if (this._skybox && !newOptions.createSkybox) {
  91953. this._skybox.dispose();
  91954. this._skybox = null;
  91955. }
  91956. if (this._skyboxMaterial && !newOptions.createSkybox) {
  91957. this._skyboxMaterial.dispose();
  91958. this._skyboxMaterial = null;
  91959. }
  91960. if (this._skyboxTexture) {
  91961. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  91962. this._skyboxTexture.dispose();
  91963. this._skyboxTexture = null;
  91964. }
  91965. }
  91966. if (this._groundMirror && !newOptions.enableGroundMirror) {
  91967. this._groundMirror.dispose();
  91968. this._groundMirror = null;
  91969. }
  91970. if (this._scene.environmentTexture) {
  91971. if (this._options.environmentTexture != newOptions.environmentTexture) {
  91972. this._scene.environmentTexture.dispose();
  91973. }
  91974. }
  91975. this._options = newOptions;
  91976. this._setupBackground();
  91977. this._setupImageProcessing();
  91978. };
  91979. /**
  91980. * Sets the primary color of all the available elements.
  91981. * @param color
  91982. */
  91983. EnvironmentHelper.prototype.setMainColor = function (color) {
  91984. if (this.groundMaterial) {
  91985. this.groundMaterial.primaryColor = color;
  91986. }
  91987. if (this.skyboxMaterial) {
  91988. this.skyboxMaterial.primaryColor = color;
  91989. }
  91990. if (this.groundMirror) {
  91991. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  91992. }
  91993. };
  91994. /**
  91995. * Setup the image processing according to the specified options.
  91996. */
  91997. EnvironmentHelper.prototype._setupImageProcessing = function () {
  91998. if (this._options.setupImageProcessing) {
  91999. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  92000. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  92001. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  92002. this._setupEnvironmentTexture();
  92003. }
  92004. };
  92005. /**
  92006. * Setup the environment texture according to the specified options.
  92007. */
  92008. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  92009. if (this._scene.environmentTexture) {
  92010. return;
  92011. }
  92012. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  92013. this._scene.environmentTexture = this._options.environmentTexture;
  92014. return;
  92015. }
  92016. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  92017. this._scene.environmentTexture = environmentTexture;
  92018. };
  92019. /**
  92020. * Setup the background according to the specified options.
  92021. */
  92022. EnvironmentHelper.prototype._setupBackground = function () {
  92023. if (!this._rootMesh) {
  92024. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  92025. }
  92026. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  92027. var sceneSize = this._getSceneSize();
  92028. if (this._options.createGround) {
  92029. this._setupGround(sceneSize);
  92030. this._setupGroundMaterial();
  92031. this._setupGroundDiffuseTexture();
  92032. if (this._options.enableGroundMirror) {
  92033. this._setupGroundMirrorTexture(sceneSize);
  92034. }
  92035. this._setupMirrorInGroundMaterial();
  92036. }
  92037. if (this._options.createSkybox) {
  92038. this._setupSkybox(sceneSize);
  92039. this._setupSkyboxMaterial();
  92040. this._setupSkyboxReflectionTexture();
  92041. }
  92042. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92043. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92044. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92045. };
  92046. /**
  92047. * Get the scene sizes according to the setup.
  92048. */
  92049. EnvironmentHelper.prototype._getSceneSize = function () {
  92050. var _this = this;
  92051. var groundSize = this._options.groundSize;
  92052. var skyboxSize = this._options.skyboxSize;
  92053. var rootPosition = this._options.rootPosition;
  92054. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92055. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92056. }
  92057. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92058. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92059. });
  92060. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92061. if (this._options.sizeAuto) {
  92062. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92063. this._scene.activeCamera.upperRadiusLimit) {
  92064. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92065. skyboxSize = groundSize;
  92066. }
  92067. var sceneDiagonalLenght = sceneDiagonal.length();
  92068. if (sceneDiagonalLenght > groundSize) {
  92069. groundSize = sceneDiagonalLenght * 2;
  92070. skyboxSize = groundSize;
  92071. }
  92072. // 10 % bigger.
  92073. groundSize *= 1.1;
  92074. skyboxSize *= 1.5;
  92075. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92076. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92077. }
  92078. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92079. };
  92080. /**
  92081. * Setup the ground according to the specified options.
  92082. */
  92083. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92084. var _this = this;
  92085. if (!this._ground) {
  92086. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92087. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92088. this._ground.parent = this._rootMesh;
  92089. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92090. }
  92091. this._ground.receiveShadows = this._options.enableGroundShadow;
  92092. };
  92093. /**
  92094. * Setup the ground material according to the specified options.
  92095. */
  92096. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92097. if (!this._groundMaterial) {
  92098. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92099. }
  92100. this._groundMaterial.alpha = this._options.groundOpacity;
  92101. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92102. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92103. this._groundMaterial.primaryLevel = 1;
  92104. this._groundMaterial.primaryColor = this._options.groundColor;
  92105. this._groundMaterial.secondaryLevel = 0;
  92106. this._groundMaterial.tertiaryLevel = 0;
  92107. this._groundMaterial.useRGBColor = false;
  92108. this._groundMaterial.enableNoise = true;
  92109. if (this._ground) {
  92110. this._ground.material = this._groundMaterial;
  92111. }
  92112. };
  92113. /**
  92114. * Setup the ground diffuse texture according to the specified options.
  92115. */
  92116. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92117. if (!this._groundMaterial) {
  92118. return;
  92119. }
  92120. if (this._groundTexture) {
  92121. return;
  92122. }
  92123. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92124. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92125. return;
  92126. }
  92127. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92128. diffuseTexture.gammaSpace = false;
  92129. diffuseTexture.hasAlpha = true;
  92130. this._groundMaterial.diffuseTexture = diffuseTexture;
  92131. };
  92132. /**
  92133. * Setup the ground mirror texture according to the specified options.
  92134. */
  92135. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92136. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92137. if (!this._groundMirror) {
  92138. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92139. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92140. this._groundMirror.anisotropicFilteringLevel = 1;
  92141. this._groundMirror.wrapU = wrapping;
  92142. this._groundMirror.wrapV = wrapping;
  92143. this._groundMirror.gammaSpace = false;
  92144. if (this._groundMirror.renderList) {
  92145. for (var i = 0; i < this._scene.meshes.length; i++) {
  92146. var mesh = this._scene.meshes[i];
  92147. if (mesh !== this._ground &&
  92148. mesh !== this._skybox &&
  92149. mesh !== this._rootMesh) {
  92150. this._groundMirror.renderList.push(mesh);
  92151. }
  92152. }
  92153. }
  92154. }
  92155. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92156. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92157. };
  92158. /**
  92159. * Setup the ground to receive the mirror texture.
  92160. */
  92161. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92162. if (this._groundMaterial) {
  92163. this._groundMaterial.reflectionTexture = this._groundMirror;
  92164. this._groundMaterial.reflectionFresnel = true;
  92165. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92166. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92167. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92168. }
  92169. };
  92170. /**
  92171. * Setup the skybox according to the specified options.
  92172. */
  92173. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92174. var _this = this;
  92175. if (!this._skybox) {
  92176. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92177. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92178. }
  92179. this._skybox.parent = this._rootMesh;
  92180. };
  92181. /**
  92182. * Setup the skybox material according to the specified options.
  92183. */
  92184. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92185. if (!this._skybox) {
  92186. return;
  92187. }
  92188. if (!this._skyboxMaterial) {
  92189. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92190. }
  92191. this._skyboxMaterial.useRGBColor = false;
  92192. this._skyboxMaterial.primaryLevel = 1;
  92193. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92194. this._skyboxMaterial.secondaryLevel = 0;
  92195. this._skyboxMaterial.tertiaryLevel = 0;
  92196. this._skyboxMaterial.enableNoise = true;
  92197. this._skybox.material = this._skyboxMaterial;
  92198. };
  92199. /**
  92200. * Setup the skybox reflection texture according to the specified options.
  92201. */
  92202. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92203. if (!this._skyboxMaterial) {
  92204. return;
  92205. }
  92206. if (this._skyboxTexture) {
  92207. return;
  92208. }
  92209. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92210. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92211. return;
  92212. }
  92213. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92214. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92215. this._skyboxTexture.gammaSpace = false;
  92216. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92217. };
  92218. /**
  92219. * Dispose all the elements created by the Helper.
  92220. */
  92221. EnvironmentHelper.prototype.dispose = function () {
  92222. if (this._groundMaterial) {
  92223. this._groundMaterial.dispose(true, true);
  92224. }
  92225. if (this._skyboxMaterial) {
  92226. this._skyboxMaterial.dispose(true, true);
  92227. }
  92228. this._rootMesh.dispose(false);
  92229. };
  92230. /**
  92231. * Default ground texture URL.
  92232. */
  92233. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92234. /**
  92235. * Default skybox texture URL.
  92236. */
  92237. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92238. /**
  92239. * Default environment texture URL.
  92240. */
  92241. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92242. return EnvironmentHelper;
  92243. }());
  92244. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92245. })(BABYLON || (BABYLON = {}));
  92246. //# sourceMappingURL=babylon.environmentHelper.js.map
  92247. "use strict";
  92248. var BABYLON;
  92249. (function (BABYLON) {
  92250. /**
  92251. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92252. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92253. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92254. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92255. */
  92256. var VideoDome = /** @class */ (function (_super) {
  92257. __extends(VideoDome, _super);
  92258. /**
  92259. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92260. * @param name Element's name, child elements will append suffixes for their own names.
  92261. * @param urlsOrVideo
  92262. * @param options An object containing optional or exposed sub element properties:
  92263. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92264. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92265. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92266. * @param options **loop=true** Automatically loop video on end.
  92267. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92268. */
  92269. function VideoDome(name, urlsOrVideo, options, scene) {
  92270. var _this = _super.call(this, name, scene) || this;
  92271. // set defaults and manage values
  92272. name = name || "videoDome";
  92273. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92274. options.clickToPlay = Boolean(options.clickToPlay);
  92275. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92276. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92277. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92278. // create
  92279. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92280. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92281. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92282. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92283. flat: false,
  92284. radius: options.size,
  92285. subdivisions: options.resolution,
  92286. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92287. }, scene);
  92288. // configure material
  92289. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92290. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92291. material.reflectionTexture = _this._videoTexture;
  92292. material.useEquirectangularFOV = true;
  92293. material.fovMultiplier = 1.0;
  92294. // configure mesh
  92295. _this._mesh.material = material;
  92296. _this._mesh.parent = _this;
  92297. // optional configuration
  92298. if (options.clickToPlay) {
  92299. scene.onPointerUp = function () {
  92300. _this._videoTexture.video.play();
  92301. };
  92302. }
  92303. return _this;
  92304. }
  92305. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92306. /**
  92307. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92308. * Also see the options.resolution property.
  92309. */
  92310. get: function () {
  92311. return this._material.fovMultiplier;
  92312. },
  92313. set: function (value) {
  92314. this._material.fovMultiplier = value;
  92315. },
  92316. enumerable: true,
  92317. configurable: true
  92318. });
  92319. /**
  92320. * Releases resources associated with this node.
  92321. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92322. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92323. */
  92324. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92325. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92326. this._videoTexture.dispose();
  92327. this._mesh.dispose();
  92328. this._material.dispose();
  92329. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92330. };
  92331. return VideoDome;
  92332. }(BABYLON.Node));
  92333. BABYLON.VideoDome = VideoDome;
  92334. })(BABYLON || (BABYLON = {}));
  92335. //# sourceMappingURL=babylon.videoDome.js.map
  92336. 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)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#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\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","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;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","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}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\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\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\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;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","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\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\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#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  92337. 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\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#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)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","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};"};
  92338. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92339. globalObject["BABYLON"] = BABYLON
  92340. return BABYLON;
  92341. });